Talentd
FleetCode
Make and follow sheets.Sign in

Reverse Odd Levels of Binary Tree solution and explanation

MediumBinary TreeBreadth-First SearchDepth-First SearchTree5 min read86.7% acceptanceUpdated 9 Apr 2026
Reverse Odd Levels of Binary Tree | Detailed | DFS | BFS | Leetcode 2415 | codestorywithMIKcodestorywithMIK · 35:14 · 8K viewsWatch on YouTube
9 more videos on this problem
  1. Reverse Odd Levels of Binary Tree | Detailed | DFS | BFS | Leetcode 2415 | codestorywithMIKcodestorywithMIK · 35:14 · 8K views
  2. Reverse Odd Levels of Binary Tree - Leetcode 2415 - PythonNeetCodeIO · 5:45 · 7K views
  3. 2415. Reverse Odd Levels of Binary Tree | Leetcode Weekly 311 | LeetCode 2415Bro Coders · 7:43 · 4K views
  4. Reverse Odd Levels of Binary Tree | Leetcode 2415Techdose · 11:07 · 3K views
  5. 2415. Reverse Odd Levels of Binary Tree | BFS | DFS | TreesAryan Mittal · 22:30 · 1K views
  6. 2415. Reverse Odd Levels of Binary Tree (Leetcode Medium)Programming Live with Larry · 7:30 · 881 views
  7. Leetcode 2415 Reverse Odd Levels of Binary TreeThinkCode · 4:58 · 607 views
  8. Leetcode 2415 Reverse Odd Levels of Binary TreeAlgorithmicIQ · 19:58 · 482 views
  9. LeetCode 2415 Reverse Odd Levels of Binary Tree | Level Order | Asked in J P Morgan , MicrosoftCode Harmony · 16:36 · 398 views
  10. LeetCode 2415 Reverse odd levels of Binary Tree Python SolutionAI Learning Corner · 8:02 · 302 views

The problem

Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.

  • For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].

Return the root of the reversed tree.

A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.

The level of a node is the number of edges along the path between it and the root node.

Example 1:

Input: root = [2,3,5,8,13,21,34]
Output: [2,5,3,8,13,21,34]
Explanation: 
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.

Example 2:

Input: root = [7,13,11]
Output: [7,11,13]
Explanation: 
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.

Example 3:

Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation: 
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.

Constraints:

  • The number of nodes in the tree is in the range [1, 214].
  • 0 <= Node.val <= 105
  • root is a perfect binary tree.

Approach overview

Problem Overview: Given the root of a perfect binary tree, reverse the node values at every odd level of the tree. Level 0 (the root) stays unchanged, level 1 gets reversed, level 2 stays the same, and so on. Only the values are swapped—tree structure remains unchanged.

Approach 1: Brute Force Method using Level Order Traversal (O(n) time, O(n) space)

This approach uses a classic Breadth-First Search to process the tree level by level. Use a queue to perform level order traversal and store nodes of the current level in an array. If the level index is odd, reverse the values in that array by swapping elements from both ends using a two-pointer technique. Then write the reversed values back into the nodes. The algorithm touches each node exactly once, so the time complexity is O(n), while the queue and temporary storage require O(n) space in the worst case.

This method is straightforward and easy to implement. It works well if you naturally think about trees in terms of levels. However, it temporarily stores an entire level of nodes, which adds extra memory overhead.

Approach 2: Optimized Symmetric DFS (O(n) time, O(h) space)

The optimized solution exploits the symmetry of a perfect binary tree. Instead of collecting values by level, traverse the tree in pairs of mirrored nodes using Depth-First Search. Start with the root's left and right children. When visiting a pair of symmetric nodes, check the current depth: if the depth is odd, swap their values. Then recursively process the pairs (left.left, right.right) and (left.right, right.left).

This technique directly swaps mirrored nodes without storing entire levels. Every node is visited once, giving O(n) time complexity. The recursion stack only grows to the height of the tree, which is O(h) (or O(log n) for a perfect tree). Because it avoids extra arrays or queues, the memory usage is significantly lower.

Recommended for interviews: The symmetric DFS approach is usually what interviewers expect. It shows you recognize the structural symmetry of a perfect binary tree and can leverage it for an efficient in-place solution. The brute force BFS method still demonstrates solid understanding of level-order traversal, but the DFS pairing technique highlights deeper tree manipulation skills.

Approach 1: Approach 1: Brute Force Method

This approach involves iterating through each conceivable solution space or list and checking which solutions satisfy the given problem. It's straightforward but may not be optimized for time complexity, making it suitable for problems with limited input sizes or as a stepping stone to more efficient methods.

```python
def print_hello_world():
    print("Hello, World!")

print_hello_world()
```
```java
public class HelloWorld {
    public static void printHelloWorld() {
        System.out.println("Hello, World!");
    }
    public static void main(String[] args) {
        printHelloWorld();
    }
}
```
```cpp
#include <iostream>

void printHelloWorld() {
    std::cout << "Hello, World!" << std::endl;
}

int main() {
    printHelloWorld();
    return 0;
}
```
```javascript
function printHelloWorld() {
    console.log("Hello, World!");
}

printHelloWorld();
```
```c
#include <stdio.h>

void printHelloWorld() {
    printf("Hello, World!\n");
}

int main() {
    printHelloWorld();
    return 0;
}
```
```csharp
using System;

class HelloWorld {
    static void PrintHelloWorld() {
        Console.WriteLine("Hello, World!");
    }
    static void Main() {
        PrintHelloWorld();
    }
}
```

This Python script defines a function to print "Hello, World!" and then calls it.

Complexity

Time Complexity: O(1)
Space Complexity: O(1)

Try this approach in the editor

Approach 2: Approach 2: Optimized Iterative Approach

This approach leverages tailored iteration strategies to resolve the problem more efficiently, especially when dealing with larger datasets. It eliminates some of the redundancies present in a brute force solution.

```python
def find_first_repeated_char(s):
    count = {}
    for ch in s:
        if ch in count:
            return ch
        count[ch] = 1
    return None

str = "programming"
print(f"First repeated character: {find_first_repeated_char(str)}")
```
```java
import java.util.HashMap;

public class FirstRepeatedCharacter {
    public static char firstRepeatedChar(String s) {
        HashMap<Character, Integer> count = new HashMap<>();
        for (char ch : s.toCharArray()) {
            count.put(ch, count.getOrDefault(ch, 0) + 1);
            if (count.get(ch) > 1) return ch;
        }
        return '\0';
    }

    public static void main(String[] args) {
        String str = "programming";
        System.out.println("First repeated character: " + firstRepeatedChar(str));
    }
}
```
```cpp
#include <iostream>
#include <unordered_map>
#include <string>

char findFirstRepeatedChar(const std::string& s) {
    std::unordered_map<char, int> count;
    for (char ch : s) {
        count[ch]++;
        if (count[ch] > 1) return ch;
    }
    return '\0';  // NULL character if no repetitions
}

int main() {
    std::string str = "programming";
    std::cout << "First repeated character: " << findFirstRepeatedChar(str) << std::endl;
    return 0;
}
```
```javascript
function findFirstRepeatedChar(s) {
    const count = {};
    for (const ch of s) {
        if (count[ch]) return ch;
        count[ch] = 1;
    }
    return null;
}

const str = "programming";
console.log(`First repeated character: ${findFirstRepeatedChar(str)}`);
```
```c
#include <stdio.h>

char* findRepeatedCharacter(char* s) {
    int count[256] = {0};
    int i = 0;
    while (s[i] != '\0') {
        count[(int)s[i]]++;
        if (count[(int)s[i]] > 1) {
            return &s[i];
        }
        i++;
    }
    return NULL;
}

int main() {
    char str[] = "programming";
    printf("First repeated character: %c\n", *findRepeatedCharacter(str));
    return 0;
}
```
```csharp
using System;
using System.Collections.Generic;

class Program {
    static char FindFirstRepeatedChar(string s) {
        Dictionary<char, int> count = new Dictionary<char, int>();
        foreach (char ch in s) {
            if (!count.ContainsKey(ch))
                count[ch] = 0;
            count[ch]++;
            if (count[ch] > 1) return ch;
        }
        return '\0';
    }

    static void Main() {
        string str = "programming";
        Console.WriteLine("First repeated character: " + FindFirstRepeatedChar(str));
    }
}
```

This Python code uses a dictionary to store and check character frequency, returning the first repeated character found.

Complexity

Time Complexity: O(n)
Space Complexity: O(1), since the ASCII character set size is fixed.

Try this approach in the editor

Approach 3: BFS

We can use the Breadth-First Search (BFS) method, using a queue q to store the nodes of each level, and a variable i to record the current level. If i is odd, we reverse the values of the nodes at the current level.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function reverseOddLevels(root: TreeNode | null): TreeNode | null {
    const q: TreeNode[] = [root];
    for (let i = 0; q.length > 0; ++i) {
        if (i % 2) {
            for (let l = 0, r = q.length - 1; l < r; ++l, --r) {
                [q[l].val, q[r].val] = [q[r].val, q[l].val];
            }
        }
        const nq: TreeNode[] = [];
        for (const { left, right } of q) {
            if (left) {
                nq.push(left);
                nq.push(right);
            }
        }
        q.splice(0, q.length, ...nq);
    }
    return root;
}
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func reverseOddLevels(root *TreeNode) *TreeNode {
	q := []*TreeNode{root}
	for i := 0; len(q) > 0; i++ {
		t := []*TreeNode{}
		for k := len(q); k > 0; k-- {
			node := q[0]
			q = q[1:]
			if i%2 == 1 {
				t = append(t, node)
			}
			if node.Left != nil {
				q = append(q, node.Left)
				q = append(q, node.Right)
			}
		}
		for l, r := 0, len(t)-1; l < r; l, r = l+1, r-1 {
			t[l].Val, t[r].Val = t[r].Val, t[l].Val
		}
	}
	return root
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
    fn create_tree(vals: &Vec<Vec<i32>>, i: usize, j: usize) -> Option<Rc<RefCell<TreeNode>>> {
        if i == vals.len() {
            return None;
        }
        Some(Rc::new(RefCell::new(TreeNode {
            val: vals[i][j],
            left: Self::create_tree(vals, i + 1, j * 2),
            right: Self::create_tree(vals, i + 1, j * 2 + 1),
        })))
    }

    pub fn reverse_odd_levels(
        root: Option<Rc<RefCell<TreeNode>>>,
    ) -> Option<Rc<RefCell<TreeNode>>> {
        let mut queue = VecDeque::new();
        queue.push_back(root);
        let mut d = 0;
        let mut vals = Vec::new();
        while !queue.is_empty() {
            let mut val = Vec::new();
            for _ in 0..queue.len() {
                let mut node = queue.pop_front().unwrap();
                let mut node = node.as_mut().unwrap().borrow_mut();
                val.push(node.val);
                if node.left.is_some() {
                    queue.push_back(node.left.take());
                }
                if node.right.is_some() {
                    queue.push_back(node.right.take());
                }
            }
            if d % 2 == 1 {
                val.reverse();
            }
            vals.push(val);
            d += 1;
        }
        Self::create_tree(&vals, 0, 0)
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Brute Force Method

Time Complexity: O(1)
Space Complexity: O(1)

Approach 2: Optimized Iterative Approach

Time Complexity: O(n)
Space Complexity: O(1), since the ASCII character set size is fixed.

BFS–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Level Order Traversal (BFS)O(n)O(n)When implementing a simple level-by-level traversal or when clarity is preferred over memory optimization
Symmetric DFS Node Pair SwappingO(n)O(h)Best for perfect binary trees where mirrored nodes can be processed together with minimal extra memory

Frequently asked questions

Is Reverse Odd Levels of Binary Tree easy or hard?

Reverse Odd Levels of Binary Tree is classified as a Medium problem. The difficulty comes from recognizing that only node values should be swapped and that the tree is perfect, which enables a symmetric traversal optimization.

Reverse Odd Levels of Binary Tree Python/Java solution

In Python or Java, the typical solution uses either a queue for level-order traversal or a recursive DFS that visits symmetric nodes. Both implementations run in O(n) time. Python solutions are often concise with recursion, while Java implementations frequently use explicit class methods for DFS.

How to solve Reverse Odd Levels of Binary Tree in O(n)?

Traverse the tree while keeping track of levels. With BFS, collect nodes at each level and reverse their values when the level index is odd. A more optimized solution uses DFS on symmetric node pairs and swaps their values directly at odd depths, ensuring each node is processed once for O(n) time.

What is the best approach for Reverse Odd Levels of Binary Tree?

The most efficient approach uses symmetric Depth-First Search on pairs of mirrored nodes. By traversing the left and right subtrees together, you can swap values whenever the current level is odd. This runs in O(n) time and only O(h) space for the recursion stack, making it more memory-efficient than storing entire levels.

Is Reverse Odd Levels of Binary Tree asked at Google/Amazon/Meta?

Binary tree transformation and traversal problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving level manipulation, mirrored traversal, or value swapping test understanding of BFS, DFS, and tree symmetry concepts.

What data structure is used in Reverse Odd Levels of Binary Tree?

The core data structure is a binary tree. Solutions commonly use a queue for Breadth-First Search or recursion/stack for Depth-First Search. The optimized approach also relies on the structural symmetry of a perfect binary tree to process mirrored node pairs.

What is the time complexity of Reverse Odd Levels of Binary Tree?

The time complexity is O(n) because every node in the binary tree is visited exactly once. Whether using BFS level traversal or symmetric DFS, the algorithm processes each node a single time while performing constant-time swaps.

Comments

Now write it yourselfClose this page and solve Reverse Odd Levels of Binary Tree in the editor, without looking.
Practise Reverse Odd Levels of Binary Tree