LeetCode 题解工作台
填充每个节点的下一个右侧节点指针
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
使用队列进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。 时间复杂度 ,空间复杂度 。其中 为二叉树的节点个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例 1:

输入:root = [1,2,3,4,5,6,7] 输出:[1,#,2,3,#,4,5,6,7,#] 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
示例 2:
输入:root = [] 输出:[]
提示:
- 树中节点的数量在
[0, 212 - 1]范围内 -1000 <= node.val <= 1000
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
解题思路
方法一:BFS
使用队列进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。
时间复杂度 ,空间复杂度 。其中 为二叉树的节点个数。
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
if root is None:
return root
q = deque([root])
while q:
p = None
for _ in range(len(q)):
node = q.popleft()
if p:
p.next = node
p = node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you recognize that the perfect-tree structure lets you connect parent.right directly to parent.next.left without searching for a neighbor?
- question_mark
Can you explain why traversing a level through next pointers replaces a BFS queue after the previous level has been connected?
- question_mark
Will you distinguish between this perfect-tree problem and the harder version where missing children break the simple cross-parent link rule?
常见陷阱
外企场景- error
Connecting only left.next = right and forgetting the cross-parent bridge right.next = parent.next.left, which leaves gaps between subtrees.
- error
Using a generic BFS explanation only, then missing the constant-space follow-up that this perfect binary tree specifically allows.
- error
Advancing to the next level incorrectly, such as moving with leftmost.next instead of leftmost.left, which breaks the vertical progression.
进阶变体
外企场景- arrow_right_alt
Populating Next Right Pointers in Each Node II, where the tree is not perfect and missing children force neighbor discovery.
- arrow_right_alt
Return the level-order traversal using next pointers after wiring, proving the horizontal links are correct without reusing the original tree edges.
- arrow_right_alt
Set previous-left pointers instead of next-right pointers, reversing the same level-linking idea and changing traversal direction.