这给出了一个包含每个根到叶子的路径的列表:
def binaryTreePaths(self, root):
from collections import deque
if root is None:
return []
queue = deque( [ [root, str(root.val)] ] )
ans = []
while queue:
front, path = queue.popleft()
if front.left is None and front.right is None:
ans += path,
continue
if front.left:
queue += [front.left, path + "->" + str(front.left.val)],
if front.right:
queue += [front.right, path + "->" + str(front.right.val)],
return ans
我不明白这是如何工作的,因为假设我们有一个2-3的树(节点1有左和右两个孩子)。在while循环后的第一行,当你popleft它时,队列再次被deque ([ ]) 。由于前是node1,前。左存在(因为node1有一个左孩子),我们再次将前.左和一个字符串附加到队列中。
所以队列是deque([node2,"stringhere"])。然后我们命中第三个if语句:由于node1确实有一个正确的孩子(node3),我们再次添加到队列中,这样队列就变成了deque([node2,"stringhere", node3,"an的string"])。
然后我们返回并点击while循环;由于队列不为空,我们有:
front, path = queue.popleft()
其中我们的队列是deque([node2,"stringhere", ndoe3,"antherstring"]),但无法在此上调用前、路径,因为队列中有4个参数。
我没得到什么?
您缺少行尾的,
,这使得添加到队列中的项目成为元组
。
正常的方法是使用append
方法
if front.left:
queue.append([front.left, path + "->" + str(front.left.val)])
if front.right:
queue.append([front.right, path + "->" + str(front.right.val)])
对于奖励积分,也可以使用str. format
if front.left:
queue.append([front.left, "{}->{}".format(path, front.left.val)])
if front.right:
queue.append([front.right, "{}->{}".format(path, front.right.val)])
并删除追加中的重复代码
for node in (front.left, front.right):
if node:
queue.append([node, "{}->{}".format(path, node.val)])