簡體   English   中英

查找二叉樹中的所有路徑

[英]Find all paths in a binary tree

我正在嘗試解決“給定二叉樹,返回所有根到葉路徑”的編碼問題。

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

我見過一種解決方案

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        allPath = []
        if root is None:
            return []
        self.find_all_paths_recursive(root, [], allPath)
        return allPath

    def find_all_paths_recursive(self, currNode, currPath, allPath):
        if currNode is None:
            return 
        currPath.append(currNode.val)
        if currNode.left is None and currNode.right is None:
            currOut = '->'.join([str(x) for x in list(currPath)])
            allPath.append(currOut)
        # traverse left sub tree
        self.find_all_paths_recursive(currNode.left, currPath, allPath)
        # traverse right sub tree
        self.find_all_paths_recursive(currNode.right, currPath, allPath)
        del currPath[-1]

運行上面的代碼給了我 ["1->2->5", "1->3"] 的答案,這是正確的。

我想通過更改if currNode.left is None and currNode.right is None:下的代碼塊if currNode.left is None and currNode.right is None:

      if currNode.left is None and currNode.right is None:
            #currOut = '->'.join([str(x) for x in list(currPath)])
            #allPath.append(currOut)
            allPath.append(currPath)

應該給我結果 [[1,2,5], [1,3]]。 但是,此更改返回了結果 [[],[]]。 我想知道為什么這不起作用?

由於您想直接添加 currPath,因此您必須在該時刻添加 currPath 的副本。

像這樣:

if currNode.left is None and currNode.right is None:
    #currOut = '->'.join([str(x) for x in list(currPath)])
    # allPath.append(currOut)
    allPath.append(list(currPath))

編輯:

如果不添加list您就是將原始列表對象添加到 allPath 中,該對象將因遞歸而更新。 添加list將制作copy of the original list objectcopy of the original list object將被保存且不會進一步更新。

遞歸是一種函數式遺產,因此以函數式風格使用它會產生最好的結果。 這意味着避免變量重新分配、其他突變和副作用。

讓我們看看以這種方式實現btree會是什么樣子。 請注意,可以在構造新節點時設置node屬性leftright -

# btree.py

def empty():
  return None

class node:
  def __init__(self, val, left = empty(), right = empty()):
    self.val = val
    self.left = left
    self.right = right

def paths(t, p = ()):
  if not t:
    return
  elif t.left or t.right:
    yield from paths(t.left, (*p, t.val))
    yield from paths(t.right, (*p, t.val))
  else:
    yield "->".join(map(str, (*p, t.val)))

現在這是你的main -

# main.py

from btree import node, empty, paths

#    1
#  /   \
# 2     3
#  \
#   5

t = node(1, node(2, empty(), node(5)), node(3))

print(list(paths(t)))
['1->2->5', '1->3']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM