这题就是在正常的广度优先搜索的栈里面加上了链表指向。比较简单的一道题。代码如下:
# 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 = []
本文介绍了一种将广度优先搜索(BFS)与链表相结合的方法,用于解决特定类型的二叉树问题。通过在BFS中利用链表指针,可以有效地遍历并连接同一层级的节点。代码实现简洁明了。

被折叠的 条评论
为什么被折叠?



