116. 填充每个节点的下一个右侧节点指针
Difficulty
Medium
Tags
二叉树
二叉树层次遍历
Star
❤
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node { int val; Node *left; Node *right; Node *next; }
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为
NULL
。初始状态下,所有 next 指针都被设置为
NULL
。进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:

输入:root = [1,2,3,4,5,6,7] 输出:[1,#,2,3,#,4,5,6,7,#] 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
提示:
- 树中节点的数量少于
4096
1000 <= node.val <= 1000
法1 宽度优先搜索
思路
同普通二叉树层次遍历一样,在每一层将当前节点的next指向该层下一个节点.
关键在于判断该节点是否为该层的最后一个节点
题解
class Solution: def connect(self, root: 'Node') -> 'Node': if root is None: return root queue = [] queue.append(root) while len(queue) > 0: temp_len = len(queue) temp_list = [] while temp_len > 0: temp_node = queue.pop(0) # 如果temp_node不是该层最后一个节点,就将temp_node.next指向队列首节点 if temp_len > 1: temp_node.next = queue[0] temp_len -= 1 if temp_node.left: queue.append(temp_node.left) if temp_node.right: queue.append(temp_node.right) return root
法2 递归
思路
因为是完全二叉树,所以需要连接的右侧指针只有下图两种:
d->e
属于同一节点的左右子树
e-f
属于不同节点的右左节点
所以递归的连接上述两种即可。

题解
""" # 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 self.buildconnect(node1=root.left, node2=root.right) return root def buildconnect(self, node1, node2): if node1 is Node or node2 is None: return // 将传入的两个节点连接 node1.next = node2 # 连接相同父节点 的两个节点 self.buildconnect(node1.left, node1.right) self.buildconnect(node2.left, node2.right) # 连接不同父节点的两个节点 self.buildconnect(node1.right, node2.left)
法3 递归2
思路
因为是完全二叉树,所以采用前序遍历,从上层开始,一层一层的连接、具体连接的时候,需要将该节点的左节点连到右节点上,右节点连到该节点右节点的左节点上。

题解
""" # 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 None if root.left: root.left.next = root.right if root.next: # 因为是完美二叉树,所以当有左子节点时必然有右子节点 root.right.next = root.next.left self.connect(root.left) self.connect(root.right) return root