没想到Populating Next Right Pointers in Each Node II新加的限制条件跟我的代码没冲突,所以用I的方法就可以同样解决II,我的确是没想到。。。代码如下:
# Definition for binary tree with next pointer.
# class TreeLinkNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if not root:
return root
a = [root]
b = []
while a != []:
for i in a:
if i.left:
b.append(i.left)
if i.right:
b.append(i.right)
if b != []:
for i in range(len(b) - 1):
b[i].next = b[i + 1]
a = b
b = []