113. 路径总和 II
题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
示例1
示例2
示例3
输入:root = [1,2], targetSum = 0
输出:[ ]
提示
树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
题解
本题考查回溯算法思想,求从根节点到叶子节点路径总和等于targetSum的所有路径,可以先将当前结点加入path且targetSum =
targetSum - root.val,再递归左右子树直至访问叶子结点,判断targetSum的值是否等于叶子节点的值。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if (root == null) {
return ans;
}
dfs(root, targetSum, path, ans);
return ans;
}
private void dfs(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> ans) {
if (root == null) {
return;
}
path.add(root.val);
if (targetSum == root.val && root.left == null && root.right == null) {
ans.add(new ArrayList<>(path));
return;
}
if (root.left != null) {
dfs(root.left, targetSum - root.val, path, ans);
path.remove(path.size() - 1);
}
if (root.right != null) {
dfs(root.right, targetSum - root.val, path, ans);
path.remove(path.size() - 1);
}
}
}