Binary Tree Upside Down
LeetCode #156
Description:
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
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
Idea:
仔细看Code吧,就是root->left
变成了新root
,左为现在root的right,右为现root。然后把老root
的两个子树设为空。
Code:
class Solution {
public:
TreeNode* upsideDownBinaryTree(TreeNode* root) {
if(root==NULL) return NULL; // if the tree is empty
// take care of the leaf
if(root->left==NULL && root->right==NULL) return root;
TreeNode *new_root = upsideDownBinaryTree(root->left);
root->left->left = root->right;
root->left->right = root;
root->left=NULL;
root->right=NULL;
return new_root;
}
};