Invert a binary tree.
4 / 2 7/\ /1 3 6 9
To
4 / 7 2/\ /9 6 3 1
Trivia:
This problem is inspired by this original tweets by Max Howell:
google:90% of our engineers with the software you wrote (Homebrew), but can ' t invert a binary tree on a Whitebo ard so fuck off.
This problem let us flip two fork tree, is one of the basic operation of the tree, not a problem. The bottom of that sentence is really some wood has moral integrity Ah, do not know is Google said to whom. Anyway, this problem is not very difficult, you can use recursion and non-recursive two methods to solve. First look at the recursive method, the writing is very concise, five lines of code, exchange the current left and right node, and directly call recursion can, code as follows:
// recursion class Solution {public: TreeNode* Inverttree (treenode* root) { if return NULL; *tmp = root-> left; Root->left = Inverttree (root-> right); Root->right = inverttree (tmp); return root;} };
Non-recursive method is not complex, with the sequence traversal of the binary tree, you need to use queue to assist, first put the root node into the queue, and then take out from the team, exchange its left and right nodes, if there are left to the side of the queue, in order to push until the queue of wood node stop cycle, return to root. The code is as follows:
//non-recursionclassSolution { Public: TreeNode* Inverttree (treenode*root) { if(!root)returnNULL; Queue<TreeNode*>Q; Q.push (root); while(!Q.empty ()) {TreeNode*node =Q.front (); Q.pop (); TreeNode*tmp = node->Left ; Node->left = node->Right ; Node->right =tmp; if(node->left) Q.push (node->Left ); if(node->right) Q.push (node->Right ); } returnRoot; }};
[Leetcode] Invert binary tree flips two forks