⚡Flashcard Drill➔
NeetCode #426LC-2415MediumTrees
← Back to All Problems

#426 · #2415 · Reverse Odd Levels of Binary Tree(反转二叉树的奇数层)

📌 Problem Statement & Constraints

Given the root of a perfect binary tree, reverse the node values at each odd level (the root is level 0). Return the root. Constraints: the number of nodes is in [1, 2^14 - 1], 1 <= Node.val <= 10^5.

💡 Core Algorithmic Approaches

  1. At an odd level, the left-to-right order of the nodes must be reversed, which pairs node i with node n-1-i.
  2. A simultaneous DFS from the leftmost and rightmost nodes of a level achieves this: swap their values, then recurse into (left.left, right.right) and (left.right, right.left).
  3. The level parity determines whether a swap happens.
  4. Because the tree is perfect, the two pointers stay aligned on the same level.

💻 Benchmark Python3 Implementation

class Solution:
    def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(left: Optional[TreeNode], right: Optional[TreeNode], level: int) -> None:
            if not left or not right:
                return
            if level % 2 == 1:
                left.val, right.val = right.val, left.val   # swap mirrored nodes
            # mirrored recursion keeps the pairs aligned on the same level
            dfs(left.left, right.right, level + 1)
            dfs(left.right, right.left, level + 1)

        if root:
            dfs(root.left, root.right, 1)   # level 1 is the first odd level
        return root

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node participates in one swap or none.
💾 Space Complexity
O(log n) for the recursion stack (the tree is perfect).

⚠️ Interview Pitfalls & Follow-ups

  • Starting the level at 0: the children are at level 1, which is the first odd level.
  • Recursing into (left.left, right.left): the mirrored pairing is left.left with right.right and left.right with right.left.
  • Reversing the node pointers instead of the values: the problem asks to reverse the values.
  • Using a level-order traversal and reversing the list: it works but allocates O(w) per level, where w is the width.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

反转二叉树的奇数层

给你一棵 完美二叉树 的根节点 root,请你反转这棵树中每个 奇数层 的节点值。例如,假设第 3 层的节点值是 [2,1,3,4,7,11,29,18] ,那么反转后它应该变成 [18,29,11,7,4,3,1,2] 。反转后,返回树的根节点。约束:树中的节点数在范围 [1, 2^14 − 1] 内;0 ≤ Node.val ≤ 10^5。

核心要点

  • 递归镜像配对交换(标准解) :同时递归「最左与最右」两个对称位置,若层号为奇数则交换它们的值。
  • 配对规则 : a.left 对应 b.right , a.right 对应 b.left ——这正是镜像对称的配对方式。
  • 层号 :根为第 0 层,其左右子节点为第 1 层,因此初始调用时层号为 1。
  • 复杂度 :O(n) 时间、O(h) 空间。

常见陷阱

  • 配对时用 a.left 配 b.left :那是同侧配对;镜像反转必须交叉配对( a.left 配 b.right )。
  • 初始层号写成 0 :根是第 0 层,其子节点是第 1 层,因此首次调用应传 1。
  • 用 BFS 逐层收集再反转 :也可行,但需要 O(w) 空间;递归交换只需 O(h)。
  • 本题只适用于完美二叉树 :非完美树需要更通用的处理。

参考实现

class Solution:
    def reverseOddLevels(self, root: 'TreeNode') -> 'TreeNode':
        def dfs(a, b, level: int) -> None:
            if not a or not b:
                return
            if level % 2 == 1:              # 奇数层 -> 交换对称位置的值
                a.val, b.val = b.val, a.val
            dfs(a.left, b.right, level + 1) # 镜像配对
            dfs(a.right, b.left, level + 1)

        if root:
            dfs(root.left, root.right, 1)   # 第 1 层开始
        return root