2415. Reverse Odd Levels of Binary Tree - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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.

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.

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
How fast can I learn coding?
Difference between "git add -A" and "git add ."
2214. Minimum Health to Beat Game - Detailed Explanation
Learn to solve Leetcode 2214. Minimum Health to Beat Game with multiple approaches.
Related Courses
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.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;