226. Invert Binary Tree

nvert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by  this original tweet  by  Max Howell :
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

Subscribe to see which companies asked this question

C++递归代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
         if(root==NULL)return NULL;
        TreeNode *treeleft=invertTree(root->right);
        TreeNode *treeright=invertTree(root->left);
        root->left=treeleft;
        root->right=treeright;
        return root;
        
    }
};

C++非递归代码,主要是BFS宽度优先搜索的思想,利用队列来实现:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL) return NULL;
        queue<TreeNode*>tree_que;
        tree_que.push(root);
        while(tree_que.size()>0)
        {
            TreeNode *first=tree_que.front();
            tree_que.pop();
            TreeNode *tmp=first->left;
            first->left=first->right;
            first->right=tmp;
            if(first->left)
                tree_que.push(first->left);
            if(first->right)
                tree_que.push(first->right);
        }
		return root;
    }
};


C#版本,顺便改了下递归顺序,另外C#版本的代码也可以在JAVA环境中运行,主要是NULL大小写的区别,C#和java是没有定义大写的NULL的。

public class Solution {
    public TreeNode InvertTree(TreeNode root) {
        if(root==null)return null;
        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        InvertTree(root.left);
        InvertTree(root.right);
   
        return root;
        
    }
}




你可能感兴趣的:(226. Invert Binary Tree)