2015-08-28 27 views
0

这使含叶每一根的路径列表:Python的双端队列和popleft(收藏模块的一部分)

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 

我不明白这是如何工作,因为说我们有一个树的1- 2-3(节点1有左右两个孩子)。在while循环之后的第一行,当你嘟嘟一声时,队列再次变为deque([])。由于front是node1并且front.left存在(因为node1有一个左边的孩子),所以我们再附加front.left和一个字符串到队列中。

那么队列是deque([node2,“stringhere”])。然后我们点击第三条if语句:因为node1有一个正确的子节点(node3),所以我们再次将队列添加到队列,这样队列变为deque([node2,“stringhere”,node3,“anothertring”])。

然后我们回去打while循环;因为队列不为空,我们有:

front, path = queue.popleft() 

在那里我们队列双端队列([节点2,“stringhere”,ndoe3,“anotherstring”]),但它不可能打电话前,道路上这一点,因为有队列中有4个参数。

我没有得到什么?

回答

2

您在行末尾缺少,,这会使项目被添加到队列tuple

方式,一般是使用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)]) 
+0

你的代码的重复'是一个天才。谢谢!!我从未想过这是逗号。 –