156. Binary Upside Down
1
/ \
2 3
/ \
4 5 4
/ \
5 2
/ \
3 1Last updated
Was this helpful?
1
/ \
2 3
/ \
4 5 4
/ \
5 2
/ \
3 1Last updated
Was this helpful?
Was this helpful?
/**
* 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* upsideDownBinaryTree(TreeNode* root) {
if(!root || !root -> left) return root;
TreeNode * newRoot = upsideDownBinaryTree(root -> left);
root -> left -> left = root -> right;
root -> left -> right = root;
root -> left = NULL;
root -> right = NULL;
return newRoot;
}
};/**
* 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* upsideDownBinaryTree(TreeNode* root) {
TreeNode* cur = root, * pre = NULL, * next= NULL, * sib = NULL;
while(cur){
next = (cur->left);
cur-> left = sib;
sib = cur -> right;
cur -> right = pre;
pre = cur;
cur = next;
}
return pre;
}
};