#2415
Reverse Odd Levels of Binary Tree
MediumTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a depth-first search (DFS) to traverse the tree and directly reverse the values at odd levels as we go. This avoids the need for additional space to store values and allows us to reverse in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Use DFS to traverse the tree, keeping track of the current level.
- 2Step 2: At odd levels, collect the values in a list.
- 3Step 3: Once the entire level is collected, reverse the list and assign the values back to the nodes.
solution.py26 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def reverseOddLevels(root):
9 def dfs(node, level):
10 if not node:
11 return
12 if level % 2 == 1:
13 if level not in odd_levels:
14 odd_levels[level] = []
15 odd_levels[level].append(node)
16 dfs(node.left, level + 1)
17 dfs(node.right, level + 1)
18
19 odd_levels = {}
20 dfs(root, 0)
21 for nodes in odd_levels.values():
22 values = [node.val for node in nodes]
23 values.reverse()
24 for i in range(len(nodes)):
25 nodes[i].val = values[i]
26 return rootℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the storage of nodes at odd levels in a map.
- 1Understanding tree traversal is crucial.
- 2Reversing values in place can save space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.