题目描述
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
來源:力扣(LeetCode)
解题思路
- DFS(Depth-First Search)深度优先:采用递归遍历所有路径
- 路径终点的判定为:当该节点无
node.left
ornode.right
时。 即判定该条路线是否符合题目赋予的值sums
- 路径终点的判定为:当该节点无
Python 代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sums: int) -> List[List[int]]:
res = []
if not root:
return res
def dfs(root, path):
# 路径终点(该节点无下一分支)
if (not root.left and not root.right) and sum(path) == sums:
res.append(path)
if root.left:
dfs(root.left, path + [root.left.val])
if root.right:
dfs(root.right, path + [root.right.val])
dfs(root, [root.val])
return res