输入:
{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":{"$id":"6","left":null,"next":null,"right":null,"val":6},"next":null,"right":{"$id":"7","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
输出:
{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":{"$id":"6","left":null,"next":null,"right":null,"val":7},"right":null,"val":6},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"7","left":{"$ref":"5"},"next":null,"right":{"$ref":"6"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"7"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
BFS模板的应用。
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
class Solution(object):
# 层序遍历
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return root
queue = [root]
# while 循环迭代的是树的层级。
while queue:
l = len(queue)
# 内部的 for 循环迭代的是同一层的所有节点
for i in range(l):
node = queue.pop(0)
# 由于可以访问同一层级的所有节点,因此能够建立 next 指针连接。
if i < l - 1:
node.next = queue[0]
"""
for 循环弹出一个节点时,同时把它的左孩子节点和右孩子节点依次加入队列。
因此队列中每个层级的元素也是顺序存储的。可以通过已有的顺序建立 next 指针。
"""
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root