Reverse Odd Levels of Binary Tree - Problem
Transform a Perfect Binary Tree by Reversing Odd Levels
Given the root of a perfect binary tree, your task is to reverse the node values at each odd-numbered level of the tree.
🌳 What makes this interesting:
• A perfect binary tree has all parent nodes with exactly two children
• All leaf nodes are at the same level
• We need to reverse values within each odd level, not the structure
For example, if level 3 contains values
Level numbering starts at 0:
• Level 0 (root): Keep as-is
• Level 1: Reverse values
• Level 2: Keep as-is
• Level 3: Reverse values
• And so on...
Return the root of the modified tree with odd levels reversed.
Given the root of a perfect binary tree, your task is to reverse the node values at each odd-numbered level of the tree.
🌳 What makes this interesting:
• A perfect binary tree has all parent nodes with exactly two children
• All leaf nodes are at the same level
• We need to reverse values within each odd level, not the structure
For example, if level 3 contains values
[2,1,3,4,7,11,29,18], after reversal it becomes [18,29,11,7,4,3,1,2].Level numbering starts at 0:
• Level 0 (root): Keep as-is
• Level 1: Reverse values
• Level 2: Keep as-is
• Level 3: Reverse values
• And so on...
Return the root of the modified tree with odd levels reversed.
Input & Output
example_1.py — Basic Perfect Binary Tree
$
Input:
root = [2,3,5,8,13,21,34]
›
Output:
[2,5,3,8,13,21,34]
💡 Note:
Level 0: [2] stays the same. Level 1: [3,5] becomes [5,3] (reversed). Level 2: [8,13,21,34] stays the same. The tree structure remains unchanged, only values at odd levels are reversed.
example_2.py — Larger Perfect Tree
$
Input:
root = [7,13,11]
›
Output:
[7,11,13]
💡 Note:
Level 0: [7] stays the same. Level 1: [13,11] becomes [11,13] (reversed). This is a simple 2-level perfect binary tree where only the children values are swapped.
example_3.py — Single Node Tree
$
Input:
root = [0]
›
Output:
[0]
💡 Note:
A tree with only one node has no odd levels to reverse (level 0 is even), so it remains unchanged. This is an edge case where the tree is trivially perfect.
Constraints
- The number of nodes in the tree is in the range [1, 214]
- 0 ≤ Node.val ≤ 105
- root is a perfect binary tree
Visualization
Tap to expand
Understanding the Visualization
1
Identify Structure
Perfect binary tree ensures complete symmetry at each level
2
Level Classification
Determine which levels are odd (1, 3, 5, ...) and need reversal
3
Symmetric Pairing
Match nodes symmetrically across each odd level
4
Value Swapping
Exchange values between symmetric pairs at odd levels
Key Takeaway
🎯 Key Insight: Perfect binary trees have symmetric structure that allows efficient in-place swapping of values at odd levels using DFS traversal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code