156. Binary Tree Upside Down
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: return the root of the binary tree [4,5,2,#,#,3,1]
4
/ \
5 2
/ \
3 1 Last updated
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: return the root of the binary tree [4,5,2,#,#,3,1]
4
/ \
5 2
/ \
3 1 Last updated
1
/ \
2 3
/
4
\
5// Recursion Method
TreeNode* upsideDownBinaryTree(TreeNode* root) { // time: O(n); space: O(n)
if (!root || !root->left) return root;
TreeNode *l = root->left, *r = root->right;
TreeNode *newRoot = upsideDownBinaryTree(l);
l->left = r; // original right node becomes left node
l->right = root; // original root becomes right node
root->left = nullptr;
root->right = nullptr;
return newRoot;
}// Iteration Method
TreeNode* upsideDownBinaryTree(TreeNode* root) { // time: O(n); space: O(1)
TreeNode *cur = root, *next = nullptr, *pre = nullptr, *tmp = nullptr;
while (cur) {
next = cur->left; // the next iteration cur node
cur->left = tmp;
tmp = cur->right; // current right node is left node in the next iteration
cur->right = pre;
pre = cur; // cur root node is the right node in the next iteration
cur = next;
}
return pre;
}