这题就是在正常的广度优先搜索的栈里面加上了链表指向。比较简单的一道题。代码如下:
# 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 = []