[英]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()
) 共:
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.