Skip to content

2415. Reverse Odd Levels of Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  TreeNode* reverseOddLevels(TreeNode* root) {
    dfs(root->left, root->right, true);
    return root;
  }

 private:
  void dfs(TreeNode* left, TreeNode* right, bool isOddLevel) {
    if (left == nullptr)
      return;
    if (isOddLevel)
      swap(left->val, right->val);
    dfs(left->left, right->right, !isOddLevel);
    dfs(left->right, right->left, !isOddLevel);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public TreeNode reverseOddLevels(TreeNode root) {
    dfs(root.left, root.right, true);
    return root;
  }

  private void dfs(TreeNode left, TreeNode right, boolean isOddLevel) {
    if (left == null)
      return;
    if (isOddLevel) {
      final int val = left.val;
      left.val = right.val;
      right.val = val;
    }
    dfs(left.left, right.right, !isOddLevel);
    dfs(left.right, right.left, !isOddLevel);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def reverseOddLevels(self, root: TreeNode | None) -> TreeNode | None:
    def dfs(left: TreeNode | None, right: TreeNode | None, isOddLevel: bool) -> None:
      if not left:
        return
      if isOddLevel:
        left.val, right.val = right.val, left.val
      dfs(left.left, right.right, not isOddLevel)
      dfs(left.right, right.left, not isOddLevel)

    dfs(root.left, root.right, True)
    return root