2415. Reverse Odd Levels of Binary Tree - Detailed Explanation

Problem Statement

You are given the root of a perfect binary tree (a binary tree in which all leaves are on the same level, and every parent has two children). Your task is to reverse the node values at every odd level of the tree (i.e., levels 1, 3, 5, …) and then return the root of the modified tree. The root is considered level 0.

For example, consider the following perfect binary tree:

         2
       /   \
      3     5
     / \   / \
    8  13 21 34
  • Level 0: [2]
  • Level 1: [3, 5] (odd level)
  • Level 2: [8, 13, 21, 34]

After reversing the nodes on the odd level (level 1), the tree becomes:

         2
       /   \
      5     3
     / \   / \
    8  13 21 34

Example 1
Input:

root = [2, 3, 5, 8, 13, 21, 34]

Output:

[2, 5, 3, 8, 13, 21, 34]

Explanation:
Only the nodes at level 1 are reversed: the nodes 3 and 5 swap their values.

Example 2
Consider a tree with three levels:
Input:

root = [7, 13, 11, 1, 4, 6, 5, 0, 9, 8, 2, 3, 10, 12, 14]

This corresponds to:

  • Level 0: [7]
  • Level 1: [13, 11]
  • Level 2: [1, 4, 6, 5]
  • Level 3: [0, 9, 8, 2, 3, 10, 12, 14]

Output:
After reversing the odd levels (levels 1 and 3), the tree becomes:

  • Level 0: [7]
  • Level 1: [11, 13]
  • Level 2: [1, 4, 6, 5]
  • Level 3: [14, 12, 10, 3, 2, 8, 9, 0]

Hints

  1. Level Order Traversal:
    You can perform a breadth-first (level order) traversal of the tree. For each odd level, collect the nodes in an array, reverse the array, and then reassign the reversed values to the nodes.

  2. Symmetric DFS (Two-Pointer Technique):
    Since the tree is perfect, every level is symmetric. You can perform a depth-first search (DFS) that traverses the tree in pairs (mirror images). At each odd level, swap the values of the paired nodes. This method avoids extra space for storing nodes and naturally exploits the tree’s symmetry.

Approach 1: Breadth-First Search (BFS)

Explanation

  • Traversal: Use level order traversal to visit all nodes level by level.

  • Collection: For each level, if it is an odd level, store the nodes’ references (or values) in an array.

  • Reversal: Reverse the collected array.

  • Assignment: Reassign the reversed values back to the nodes on that level.

Drawbacks

  • You need extra space to store the nodes of each level.
  • Although intuitive, it involves multiple passes: one for collecting values and one for reassigning them.

Approach 2: Depth-First Search (DFS) with Two-Pointer Technique (Optimal)

Explanation

  • Pairing: Start by pairing the left and right children of the root (level 1).
  • Swapping on Odd Levels: For any pair of nodes at the same odd level, swap their values.
  • Recursive Traversal: Recurse on the next level by pairing:
    • The left child of the first node with the right child of the second node.

    • The right child of the first node with the left child of the second node.

  • Stop Condition: When you reach the leaf nodes, stop the recursion.

Benefits

  • Space Efficiency: This method works in-place and only uses O(h) extra space (the recursion stack), where h is the tree height.

  • Time Efficiency: The entire tree is visited once, leading to O(n) time complexity.

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:
    • Both approaches traverse each node exactly once.
    • Overall time complexity is O(n), where n is the number of nodes in the tree.
  • Space Complexity:
    • For DFS, the space is O(h) due to recursion, where h is the height of the tree (O(log n) for a perfect binary tree).
    • BFS would use O(n) in the worst case to store nodes at the last level.

Step-by-Step Walkthrough (DFS Approach)

  1. Initial Call:
    • Start by calling the helper function with the left and right children of the root at level 1.
  2. At Level 1 (Odd):
    • Swap the values of the paired nodes (e.g., swap 3 and 5).
  3. Recurse to Next Level:
    • Process the pairs (node1.left with node2.right and node1.right with node2.left) for level 2.
  4. Continue Recursion:
    • When the level is even, do not swap values; just continue the DFS.
  5. Termination:
    • When reaching leaf nodes (or null children), stop the recursion.
  6. Return:
    • The tree is modified in place and returned.

Common Mistakes and Edge Cases

  • Incorrect Level Counting:
    • Ensure that the root is at level 0 so that its children are correctly identified as level 1 (an odd level).
  • Null Checks:
    • Always check for null nodes before attempting to access or swap values.
  • Assumption of Perfect Tree:
    • The DFS pairing approach assumes a perfect binary tree. If the tree is not perfect, additional checks are required.

Alternative Variations

  • BFS-Based Reversal:
    • Instead of DFS, perform a level order traversal, collect nodes at odd levels into a list, reverse the list, and then assign the reversed values back.
  • Iterative DFS:
    • Use a stack to simulate the recursive DFS if recursion is a concern.
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
128. Longest Consecutive Sequence - Detailed Explanation
Learn to solve Leetcode 128. Longest Consecutive Sequence with multiple approaches.
2444. Count Subarrays With Fixed Bounds - Detailed Explanation
Learn to solve Leetcode 2444. Count Subarrays With Fixed Bounds with multiple approaches.
17. Letter Combinations of a Phone Number - Detailed Explanation
Learn to solve Leetcode 17. Letter Combinations of a Phone Number with multiple approaches.
1028. Recover a Tree From Preorder Traversal - Detailed Explanation
Learn to solve Leetcode 1028. Recover a Tree From Preorder Traversal with multiple approaches.
151. Reverse Words in a String - Detailed Explanation
Learn to solve Leetcode 151. Reverse Words in a String with multiple approaches.
1497. Check If Array Pairs Are Divisible by k - Detailed Explanation
Learn to solve Leetcode 1497. Check If Array Pairs Are Divisible by k with multiple approaches.
Related Courses
Course image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
Discounted price for Your Region

$197

Course image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$78

Course image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Image
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.