Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2415: Reverse Odd Levels of Binary Tree

LeetCode 2415 Solution 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.

LeetCode 2415 Solutions in Java, C++, Python

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);
    }
}

Interactive Code Editor for LeetCode 2415

Improve Your LeetCode 2415 Solution

Use the editor below to refine the provided solution for LeetCode 2415. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems