Nvert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
To
4
/ \
9 |
/ \ / \
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 whiteboard so Fuck off.
Hide Tags Tree
Although do not know homebrew why things, but Google 90% of people use the product is absolutely tall, so estimate and this trivia as Max Howell in sell moe.
Solution One
Inversion two fork tree using recursive implementation, it can be seen that if the Saozi right subtree is reversed, it is only necessary to exchange its left and the sub-tree nodes can be. The inverse of the rotor tree and reverse it itself is the same problem, so you can use recursive implementations.
Runtime:4ms
/** * Definition forA binary tree node. * struct TreeNode {*intVal * TreeNode * Left; * TreeNode * Right; * TreeNode (intx): Val (x), Left(NULL), Right(NULL) {} * }; */classSolution { Public: treenode* inverttree (treenode* root) {if(root==NULL) returnNULL; TreeNode * lefttree=NULL; TreeNode * righttree=NULL;if(root-> Left) Lefttree=inverttree (root-> Left);if(root-> Right) Righttree=inverttree (root-> Right); Root-> Left=righttree; Root-> Right=lefttree; return root; }};
Solution Two
This problem can also use non-recursive implementation, non-recursive implementation code may be a little more, but also very well understood. Using a queue, the root node is added to the queue at the beginning, then the left and right child nodes are exchanged and the root node is ejected from the queue, and if the left and right child nodes are non-empty, the left and right child nodes are joined to the queue and processed until there are no elements in the queue. Reference answers to: https://leetcode.com/discuss/40567/my-c-codes-recursive-and-nonrecursive
runtime:0ms
From the running time can be seen to study the non-recursive solution is still very meaningful.
class solution {public : treenode* inverttree (treenode* root) {queue <treenode *> Tbpnode; if (root) Tbpnode.push (root); TreeNode *curnode, *temp; while (!tbpnode.empty ()) {Curnode = Tbpnode.front (); Tbpnode.pop (); temp = curnode->left; Curnode->left = curnode->right; Curnode->right = temp; if (curnode->left) Tbpnode.push (curnode->left); if (curnode->right) Tbpnode.push (curnode->right); } return root; } }
Leetcode226:invert Binary Tree