LeetCode 题解工作台

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

给定一个二叉树: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL 。 初始状态下,所有 next …

category

5

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们使用队列 进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。 时间复杂度 ,空间复杂度 。其中 为二叉树的节点个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二叉树:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

初始状态下,所有 next 指针都被设置为 NULL

 

示例 1:

输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。

示例 2:

输入:root = []
输出:[]

 

提示:

  • 树中的节点数在范围 [0, 6000]
  • -100 <= Node.val <= 100

进阶:

  • 你只能使用常量级额外空间。
  • 使用递归解题也符合要求,本题中递归程序的隐式栈空间不计入额外空间复杂度。
lightbulb

解题思路

方法一:BFS

我们使用队列 qq 进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为二叉树的节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
# 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: "Node") -> "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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you see how missing children affect the next pointer connections across levels?

  • question_mark

    Can you implement this without using extra memory while still connecting all nodes correctly?

  • question_mark

    Will you traverse the tree level by level or rely on recursion to handle next pointer assignments?

warning

常见陷阱

外企场景
  • error

    Forgetting to handle the end of a level, leaving the last node's next pointer incorrectly pointing to a non-null value.

  • error

    Assuming the tree is perfect and not handling missing children, which breaks cross-level connections.

  • error

    Using recursion in the wrong order (left before right), causing next pointers to reference null instead of the correct neighbor.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Populating Next Right Pointers in Each Node (perfect binary tree version) with O(1) space requirements.

  • arrow_right_alt

    Level Order Traversal of Binary Tree with pointers returned as linked lists per level.

  • arrow_right_alt

    Flatten Binary Tree to Linked List in-place, connecting nodes in pre-order with similar pointer manipulations.

help

常见问题

外企场景

填充每个节点的下一个右侧节点指针 II题解:链表指针操作 | LeetCode #117 中等