Given a binary tree where all the right nodes is either leaf nodes with a sibling (a left node that shares the same paren T node) or empty, flip it upside down and turn it to a tree where the original right nodes turned to left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
Return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \
3 1
This problem let us put a binary tree upside down, and limit the right node is either empty or there must be a corresponding left node. Upside down after the original two fork tree the left child node becomes the root node, its corresponding right node becomes its left child node, its parent node becomes its right child node, equivalent to rotate clockwise. For the general tree problems will have iterative and recursive two solutions, the problem is no exception, then we first look at the recursive solution. For a root node, our goal is to turn its left child node into a root node, the right child node becomes the left child node, the original root node becomes the right child node, then we first determine whether the root node exists, and it has no left child node, if not meet these two conditions, directly return can, do not need to flip operation. So we keep calling the recursive function on the left Dial hand node until the leftmost child node starts to flip, flipping the leftmost child node, and starting to go back to the last left child node and continue flipping until the complete tree is flipped, see the code below:
Solution One:
//recursionclassSolution { Public: TreeNode*upsidedownbinarytree (TreeNode *root) { if(!root | |!root->left)returnRoot; TreeNode*l = root->left, *r = root->Right ; TreeNode*res =Upsidedownbinarytree (L); L->left =R; L->right =Root; Root->left =NULL; Root->right =NULL; returnRes; }};
Let's take a look at the iterative method, which, contrary to the recursive method, starts flipping from top to bottom until it flips to the leftmost child node, see the code below:
Solution Two:
//iterativeclassSolution { Public: TreeNode*upsidedownbinarytree (TreeNode *root) {TreeNode*cur = root, *pre = null, *next = NULL, *tmp =NULL; while(cur) {Next= cur->Left ; Cur->left =tmp; TMP= cur->Right ; Cur->right =Pre; Pre=cur; Cur=Next; } returnPre; }};
Resources:
Https://leetcode.com/discuss/18410/easy-o-n-iteration-solution-java
Https://leetcode.com/discuss/52414/c-recursive-solution-easy-understanding
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Binary tree Upside down two fork trees upside down