1.填充每个节点的下一个右侧节点指针
这道题核心在于如何使得左子树的右孩子指向右子树的左孩子,因为这两个节点之间不是同一个父节点
非递归解法,使用广度优先遍历,也就是层序遍历,在遍历每层的时候为next赋值
#使用广度优先遍历,广度优先遍历的详解
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
que = deque([root])
while len(que) != 0:
len_que = len(que)
while len_que != 0:
stack = que.popleft()
left = stack.left
if left:
que.append(left)
#核心处理
left.next = stack.right
right = stack.right
if right:
que.append(right)
#核心处理
if stack.next:
right.next = stack.next.left
len_que -= 1
return root
递归解法,很容易得到以下代码
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
def link(root: 'Node'):
if not root:
return None
if root.left:
root.left.next = root.right
if root.next and root.right:
root.right.next = root.next.left
link(root.left)
link(root.right)
return root
return link(root)