【发布时间】:2021-09-19 08:25:20
【问题描述】:
我正在编写一个 dfs 函数,它返回叶节点的所有路径。
4
/ \
9 0
/ \
1 5
此列表的预期输出为:[[4,9,5],[4,9,1],[4,0]]
这是我目前所拥有的:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def leafNodePaths(self, root):
paths = []
self.dfs(root, [], paths)
print(paths)
def dfs(self, root, current_path, paths):
if not root:
return
current_path.append(root.val)
if not root.left and not root.right:
paths.append(current_path)
else:
self.dfs(root.left, current_path, paths)
self.dfs(root.right, current_path, paths)
我得到的结果是[[4, 9, 5, 1, 0], [4, 9, 5, 1, 0], [4, 9, 5, 1, 0]]
如何保持current_path的准确计数
【问题讨论】:
-
请分享可重现的代码,包括您的节点。
-
已更新。正在尝试解决这个 leetcode 问题 (leetcode.com/problems/binary-tree-paths)
标签: python recursion depth-first-search