题目
题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
提示:
树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
题解
要找出所有从根节点到叶子节点路径总和等于给定目标和 targetSum
的路径,可以使用深度优先搜索(DFS)的方法。具体来说,通过递归遍历树的每个节点,并在遍历过程中记录当前路径及其累积和,当到达叶子节点时检查累积和是否等于目标和。
解决方案
- 定义辅助函数:用于执行深度优先搜索并记录当前路径。
- 基本情况:
- 如果当前节点为空,直接返回。
- 如果当前节点是叶子节点,则检查其值是否等于剩余的目标和。如果相等,则将当前路径加入结果列表中。
- 递归情况:
- 对于非叶子节点,更新当前路径和剩余的目标和,然后递归地对左右子树进行搜索。
Python 实现
def pathSum(root: TreeNode, targetSum: int):
result = []
def dfs(node, current_path, remaining_sum):
if not node:
return
# Add the current node to the path
current_path.append(node.val)
remaining_sum -= node.val
# Check if it's a leaf node and the path sum equals the target sum
if not node.left and not node.right and remaining_sum == 0:
result.append(list(current_path))
# Recur for left and right subtrees
dfs(node.left, current_path, remaining_sum)
dfs(node.right, current_path, remaining_sum)
# Backtrack: remove the current node from the path to explore other paths
current_path.pop()
dfs(root, [], targetSum)
return result
复杂度分析
- 时间复杂度:O(n),其中 n 是树中节点的数量。每个节点都被访问一次。
- 空间复杂度:取决于递归调用栈的深度以及存储路径的空间。在最坏情况下(树完全不平衡),空间复杂度可能达到 O(n);对于平衡树,平均空间复杂度为 O(log n)。
这种方法利用了深度优先搜索来遍历所有可能的路径,并在找到满足条件的路径时将其记录下来。通过回溯法(即在递归返回前撤销当前选择),我们能够有效地探索所有路径而不会重复计算。