题目
思路
递归,遍历当前节点的next,找到next最左子节点,把当前节点最右子节点连接到next最左子节点。
代码
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root:
if root.left and root.right:
root.left.next = root.right
lastNode = root.right
elif root.left: lastNode = root.left
else: lastNode = root.right
if lastNode:
node = root.next
while node:
if node.left:
lastNode.next = node.left; break
if node.right:
lastNode.next = node.right; break
node = node.next
if root.right: self.connect(root.right)
if root.left: self.connect(root.left)