#Leet Code# Populating Next Right Pointers in Each Node II

时间:2023-03-09 01:34:57
#Leet Code# Populating Next Right Pointers in Each Node II

描述:注意需要先self.connect(right)再self.connect(left),否则会有case通不过,原因是左边递归执行时依赖与右边的next已经建立,而先执行connect(left)的话右边还没有完成关系的建立。

代码:

 class Solution:
# @param root, a tree node
# @return nothing
def doSth(self, nextNode, conNode):
while nextNode is not None:
if nextNode.left is None and nextNode.right is None:
nextNode = nextNode.next
elif nextNode.left is not None:
conNode.next = nextNode.left
break
else:
conNode.next = nextNode.right
break def connect(self, root):
if root is None:
return if root.left is None and root.right is None:
return
elif root.left is None and root.right is not None:
self.doSth(root.next, root.right)
elif root.left is not None and root.right is None:
self.doSth(root.next, root.left)
else:
root.left.next = root.right
self.doSth(root.next, root.right) self.connect(root.right)
self.connect(root.left)