156. Binary Tree Upside Down
Problem description:
Given the root
of a binary tree, turn the tree upside down and return the new root.
You can turn a binary tree upside down with the following steps:
- The original left child becomes the new root.
- The original root becomes the new right child.
- The original right child becomes the new left child.
The mentioned steps are done level by level, it is guaranteed that every node in the given tree has either 0 or 2 children.
Example 1:
1 | Input: root = [1,2,3,4,5] |
Example 2:
1 | Input: root = [] |
Example 3:
1 | Input: root = [1] |
Constraints:
- The number of nodes in the tree will be in the range
[0, 10]
. 1 <= Node.val <= 10
- Every right node in the tree has a sibling (a left node that shares the same parent).
Solution:
As the recursive solution, we will keep recurse on the left child and once we are are done, we found the newRoot, which is 4 for this case. At this point, we will need to set the new children for node 2, basically the new left node is 3, and right node is 1. Here is the recursive solution:
1 | class Solution: |
For the iterative solution, it follows the same thought, the only thing we need to pay attention to is to save the node information that will be overwritten.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
https://leetcode.com/problems/binary-tree-upside-down/discuss/49406/Java-recursive-(O(logn)-space)-and-iterative-solutions-(O(1)-space)-with-explanation-and-figure
related problem: