【发布时间】:2020-11-24 01:13:52
【问题描述】:
我正在尝试解决“给定二叉树,返回所有从根到叶的路径”的编码问题。
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:
#currOut = '->'.join([str(x) for x in list(currPath)])
#allPath.append(currOut)
allPath.append(currPath)
应该给我结果 [[1,2,5], [1,3]]。但是,此更改为我返回了结果 [[],[]]。我想知道为什么这不起作用?
【问题讨论】: