2015-08-28 25 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

你的代碼的重複'是一個天才。謝謝!!我從未想過這是逗號。 –