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


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 not root:return
# 存在左儿子,将左儿子的next指向右儿子
if root.left:
root.left.next = root.right
# 注意这里,如果root.next存在,表示root同城右边还有节点
# 就需要将root的右儿子指向root右边节点的左儿子
if root.next:
root.right.next = root.next.left
# 注意这里一定要先递归左子树
self.connect(root.left)
self.connect(root.right)
return root
# 迭代的方法
# 过程跟递归很类似。
def connect(self, root: 'Node') -> 'Node':
# 重新定义一个变量,用于遍历二叉树
node1 = root
# 进行循环
while node1:
# 重新定义一个变量,用于遍历当前层节点
node2 = node1
while node2:
# 左儿子存在,指向右儿子
if node2.left:
node2.left.next = node2.right
# 当前节点存在右边节点,而且右儿子存在
# 就需要将当前节点的右儿子指向当前节点右边节点的左儿子
if node2.next and node2.right :
node2.right.next = node2.next.left
# 遍历下一个节点
node2 = node2.next
# 注意这里要指向左儿子
node1 = node1.left
return root

猜你喜欢

转载自www.cnblogs.com/cong12586/p/13209197.html