提示:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
与leetcode116. 填充每个节点的下一个右侧节点指针相比,这个不是完美二叉树。所以对每个root要找它的root.next,根据这个才能找到子节点的next:
"""
# 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':
if not root:
return None
if not root.left and not root.right:
return root
node_next = self.get_next_node(root.next)
if root.left and root.right:
root.left.next = root.right
root.right.next = node_next
elif root.left:
root.left.next = node_next
else:
root.right.next = node_next
self.connect(root.right) # 注意要先连接右边,不然左边找的node_next为空
self.connect(root.left)
return root
def get_next_node(self, node): # 当前子节点的next
while node:
if node.left:
return node.left
if node.right:
return node.right
node = node.next
return node