簡體   English   中英

在二叉樹中找到所有從根到葉的路徑(在Python中)

[英]Find all root to leaf paths in a binary tree (in Python)

我在Python中有一些代碼,應該以列表的形式(例如[“ 1-> 2-> 5”,“ 1-> 3”])以二進制樹的形式返回所有根到葉路徑。 最初的問題來自leetcode。

我需要幫助找出我的代碼和/或替代解決方案出了什么問題(最好在Python中)。 對於我上面給出的示例,我的代碼返回null,而實際上應該打印我給出的列表。 當您初次看到該問題時,我也非常感謝您提供的洞察力。

這是我的代碼:

    def binaryTreePaths(self, root):
        list1 = []
        if (root == None): 
            return []
        if (root.left == None and root.right == None):
            return list1.append(str(root.val) + "->") 
        if (root.left != None):
            list1.append(self.binaryTreePaths(root.left)) 
        if (root.right != None):
            list1.append(self.binaryTreePaths(root.right))
  • 遺失的退貨聲明
  • 下層遞歸返回列表,而不是單個值(即+= vs. .append()
  • 下級遞歸調用返回的列表中的值應以“ root->”開頭

共:

def binaryTreePaths(self, root):
    if root is None: 
        return []
    if (root.left == None and root.right == None):
        return [str(root.val)]
    # if left/right is None we'll get empty list anyway
    return [str(root.val) + '->'+ l for l in 
             self.binaryTreePaths(root.right) + self.binaryTreePaths(root.left)]

UPD :上面的解決方案使用列表推導 ,這是我們非常喜歡Python的原因之一。 這是擴展版本:

def binaryTreePaths(self, root):
    if root is None: 
        return []
    if (root.left == None and root.right == None):
        return [str(root.val)]

    # subtree is always a list, though it might be empty 
    left_subtree = self.binaryTreePaths(root.left)  
    right_subtree = self.binaryTreePaths(root.right)
    full_subtree = left_subtree + right_subtree  # the last part of comprehension

    list1 = []
    for leaf in full_subtree:  # middle part of the comprehension
        list1.append(str(root.val) + '->'+ leaf)  # the left part 

    return list1

暫無
暫無

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

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