Problem
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.
Examples
Example 1:
|
|
Clarification:
Confused what [4,5,2,#,#,3,1]
means? Read more below on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
|
|
The above binary tree is serialized as [1,2,3,#,#,4,#,#,5]
.
Solution
So, in the upside-down transformation logic:
- The left child becomes the parent of the current node.
- The right child becomes the left leaf of the former left child.
- The current node becomes the right leaf.
The flipping continues until the root becomes the last left child in the original tree.
Method 1 - Iterative
The process involves restructuring node connections iteratively while traversing top-down.
- Keep track of previously processed nodes (
prev
) and their parent relationships. - For each node:
- Store its left and right children temporarily.
- Establish the flipped relationships based on the transformation rules.
- Update the pointers recursively or iteratively until all nodes are processed.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. The algorithm traverses the tree once, processing each node. Thus,O(n)
, wheren
is the total number of nodes. - 🧺 Space complexity:
O(1)
. Since the operation happens in-place and uses a constant amount of extra variables, the space complexity isO(1)
.