Problem
Given the root
of a perfect binary tree, reverse the node values at each odd level of the tree.
- For example, suppose the node values at level 3 are
[2,1,3,4,7,11,29,18]
, then it should become[18,29,11,7,4,3,1,2]
.
Return the root of the reversed tree.
A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.
The level of a node is the number of edges along the path between it and the root node.
Examples
Example 1:
graph LR subgraph Input A1[2] A1 --> B1[[3]] A1 --> C1[[5]] B1 --> D1[8] B1 --> E1[13] C1 --> F1[21] C1 --> G1[34] style B1 fill:#FFD580,stroke:#333,stroke-width:2px style C1 fill:#ADD8E6,stroke:#333,stroke-width:2px end subgraph Output A2[2] A2 --> B2[[5]] A2 --> C2[[3]] B2 --> F2[34] B2 --> G2[21] C2 --> D2[8] C2 --> E2[13] style C2 fill:#FFD580,stroke:#333,stroke-width:2px style B2 fill:#ADD8E6,stroke:#333,stroke-width:2px end Input --> Output
|
|
Example 2:
graph LR subgraph Input A1[7] A1 --> B1[[13]] A1 --> C1[[11]] style B1 fill:#FFD580,stroke:#333,stroke-width:2px style C1 fill:#ADD8E6,stroke:#333,stroke-width:2px end subgraph Output A2[7] A2 --> B2[[11]] A2 --> C2[[13]] style C2 fill:#FFD580,stroke:#333,stroke-width:2px style B2 fill:#ADD8E6,stroke:#333,stroke-width:2px end Input --> Output
|
|
Example 3:
|
|
Constraints:
- The number of nodes in the tree is in the range
[1, 214]
. 0 <= Node.val <= 10^5
root
is a perfect binary tree.
Solution
Method 1 - BFS
To reverse the node values at each odd level of a perfect binary tree, we can perform a level-order traversal (BFS - Breadth-First Search) while keeping track of the nodes at each level. For each odd level, we reverse the node values.
Here is the approach:
- Perform a BFS traversal to access nodes level by level.
- Store the nodes at each level.
- For each odd level, reverse the values of the nodes.
- Assign the reversed values back to the corresponding nodes.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, as the algorithm requires traversing each node once - 🧺 Space complexity:
O(n)
uses extra space to store nodes by levels,