我试图打印二叉树的所有路径(根到叶路径),但无济于事。打印二叉树(DFS)的所有路径
我的策略是使用递归,其基本情况为either tree is None or tree node is leaf return
否则,遍历树的左侧和右侧。
但我找不到保留左右树的方法。
def pathSum(self, root, target, result):
if not root:
return []
if not root.left and not root.right:
return [root.val]
for i in [root.left, root.right]:
path = [root.val] + self.pathSum(i, target, result)
print("path", path)
return path
请定义一个“路径” - 它是一个树的遍历,或从根到叶的路径? –
一个路径是一个根叶路径 – jen007
我认为这应该是非常类似于预购遍历 – jen007