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 [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
Reverse Odd Levels of Binary Tree INPUT Perfect Binary Tree 2 Level 0 3 5 Level 1 (odd) 8 13 21 34 Level 2 root = [2,3,5,8,13,21,34] Even Level Odd Level ALGORITHM (DFS) 1 Start DFS Traversal Track level and pair nodes 2 Check Level Parity If odd level: swap values Level 1: [3, 5] --> SWAP --> Level 1: [5, 3] 3 Recurse to Children Pair left-left with right-right Pair left-right with right-left 4 Return Modified Tree Even levels unchanged Time: O(n) | Space: O(h) h = height of tree FINAL RESULT Modified Binary Tree 2 Level 0 5 3 Level 1 REVERSED 8 13 21 34 Level 2 (unchanged) output = [2,5,3,8,13,21,34] OK - Complete Key Insight: DFS pairs mirror nodes at each level: left subtree's leftmost with right subtree's rightmost. At odd levels, swap the values of paired nodes. This maintains tree structure while reversing values. Perfect binary tree property ensures equal nodes at each level for complete pairing. TutorialsPoint - Reverse Odd Levels of Binary Tree | DFS Approach
Asked in
Microsoft 25 Amazon 18 Google 15 Meta 12
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen