LeetCode 2415: Reverse Odd Levels of Binary Tree Solution

Master LeetCode problem 2415 (Reverse Odd Levels of Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2415. Reverse Odd Levels of Binary Tree

Problem Explanation

Explanation

To solve this problem, we can perform a depth-first traversal of the binary tree and reverse the node values at each odd level. We can keep track of the current level while traversing the tree and reverse the values when we encounter an odd level.

  1. Perform a depth-first traversal of the binary tree, keeping track of the current level.
  2. When visiting a node, check if the level is odd. If it is odd, reverse the values of the nodes at that level.
  3. Recur for the left and right subtrees, incrementing the level as we go deeper.
  4. Return the modified root of the binary tree.

Time Complexity: O(N) where N is the number of nodes in the binary tree. Space Complexity: O(H) where H is the height of the binary tree.

Solution Code

class Solution {
    public TreeNode reverseOddLevels(TreeNode root) {
        reverseOddLevelsHelper(root, 1);
        return root;
    }
    
    private void reverseOddLevelsHelper(TreeNode node, int level) {
        if (node == null) {
            return;
        }
        
        if (level % 2 == 1) {
            reverseValues(node);
        }
        
        reverseOddLevelsHelper(node.left, level + 1);
        reverseOddLevelsHelper(node.right, level + 1);
    }
    
    private void reverseValues(TreeNode node) {
        if (node == null) {
            return;
        }
        
        TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
        
        reverseValues(node.left);
        reverseValues(node.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2415 (Reverse Odd Levels of Binary Tree)?

This page provides optimized solutions for LeetCode problem 2415 (Reverse Odd Levels of Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2415 (Reverse Odd Levels of Binary Tree)?

The time complexity for LeetCode 2415 (Reverse Odd Levels of Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2415 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2415 in Java, C++, or Python.

Back to LeetCode Solutions