⚡Flashcard Drill➔
NeetCode #417LC-116MediumTrees
← Back to All Problems

#417 · #116 · Populating Next Right Pointers in Each Node(填充每个节点的下一个右侧节点指针)

📌 Problem Statement & Constraints

You are given a perfect binary tree where all leaves are at the same depth and every parent has two children. Each node has an extra next pointer; populate it so each node points to the next node on the same level, with the last node of each level pointing to None. Constraints: the number of nodes is in [0, 2^12 - 1].

💡 Core Algorithmic Approaches

  1. Process the tree level by level using the next pointers themselves -- no queue is needed, so the extra space is O(1).
  2. For each level, walk the chain of parents and connect: left.next = right, and right.next = parent.next.left when the parent has a next.
  3. The second connection is the crucial one: it links across different parents on the same level.
  4. Then descend via leftmost = leftmost.left.

💻 Benchmark Python3 Implementation

class Solution:
    def connect(self, root: "Optional[Node]") -> "Optional[Node]":
        if not root:
            return None
        leftmost = root
        while leftmost.left:               # while there is a level below
            head = leftmost
            while head:
                # connect the two children of this parent
                head.left.next = head.right
                # connect across parents on the same level
                if head.next:
                    head.right.next = head.next.left
                head = head.next           # move along the current level
            leftmost = leftmost.left       # descend one level
        return root

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(1) extra: the level chain is traversed through the next pointers.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the cross-parent connection: without head.right.next = head.next.left, the levels would break between subtrees.
  • Using a BFS queue: it works but costs O(n) space, while the pointer-based traversal needs O(1).
  • Connecting head.right.next = head.next: that links to a node on the same level but the wrong one; the target is head.next.left.
  • Looping while head without descending: the traversal would never reach the lower levels.
⚡
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

中文速览与面试要点

填充每个节点的下一个右侧节点指针

给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:struct Node int val; Node *left; Node *right; Node *next; 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。初始状态下,所有 next 指针都被设置为 NULL。 进阶 :你只能使用常量级额外空间。使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。约束:树中节点的数量在 [0, 2^12 − 1] 内;-1000 ≤ Node.val ≤ 1000。

核心要点

  • 利用已建立的 next 指针(O(1) 空间,标准解) :按层处理,每层从左到右用 next 指针串联。对节点 head : head.left.next = head.right ;若 head.next 存在,则 head.right.next = head.next.left 。
  • 为什么能 O(1) 空间 :上一层已建立的 next 指针天然提供了「下一个待处理节点」,无需队列。
  • 完美二叉树的前提 :每个非叶子节点都有左右子节点,因此 head.left 与 head.right 一定存在, head.next.left 也一定存在。
  • 复杂度 :O(n) 时间、O(1) 空间。

常见陷阱

  • 忘记 if head.next 的判断 :每层最右节点的 next 为 None,访问 head.next.left 会报错。
  • 用 BFS 队列 :O(w) 空间,不满足「常量级额外空间」的进阶要求。
  • leftmost = leftmost.left 的时机 :必须在处理完当前层之后才下移,本解通过外层 while 的顺序保证。
  • 本题只适用于完美二叉树 :若树不完美(如 117 题),需要更通用的写法。

参考实现

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None
        leftmost = root                        # 当前层最左节点
        while leftmost.left:                   # 还有下一层
            head = leftmost
            while head:
                head.left.next = head.right    # 同一父节点下的左右相连
                if head.next:
                    head.right.next = head.next.left   # 跨父节点相连
                head = head.next               # 借助已建立的 next 移动
            leftmost = leftmost.left           # 进入下一层
        return root