"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
self.f(root)
return root
def f(self, root):
if root == None:
return
if root.left != None and root.right != None:
root.left.next = root.right
root.right.next = root if root.next != None else None
elif root.left == None and root.right != None:
root.right.next = root if root.next != None else None
else:
if root.left != None and root.right == None:
root.left.next = root if root.next != None else None
if root.next != None :
if root.next.right == root:
cur = root.next.next
# 第29行
while cur != None and (cur.left == None and cur.right == None):
cur = cur.next
if cur == None:
root.next = cur
else:
root.next = cur.left if cur.left else cur.right
else:
if root.next.left == root:
cur = root.next.next
# 第38行
while cur != None and (cur.left == None and cur.right == None):
cur = cur.next
if cur == None:
root.next = cur
else:
root.next = cur.left if cur.left else cur.right
# 1.先便利右子树
# 2.若先遍历左子树,会使得第29行和38行逻辑出错
# 3.反例如上图中的2个例子
# 4.必须使得树的右上部分完成next连接,这样才能使得29 38行逻辑不出错
self.f(root.right)
self.f(root.left)