给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
样例描述 思路DFS + 减法
- 只有当达到叶子结点,并且targetSum减为0时,就加入到结果集。
- 遍历左右子树,记得恢复现场
class Solution {
List> res = new ArrayList<>();
List path = new ArrayList<>();
public List> pathSum(TreeNode root, int targetSum) {
dfs(root, targetSum);
return res;
}
public void dfs(TreeNode root, int targetSum) {
if (root == null) return;
path.add(root.val);
targetSum -= root.val;
//如果到达叶子结点并且targetSum减为0了
if (root.left == null && root.right == null && targetSum == 0) {
res.add(new ArrayList<>(path));
}
//存在左右子树就行进行遍历
if (root.left != null) dfs(root.left, targetSum);
if (root.right != null) dfs(root.right, targetSum);
//恢复现场
path.remove(path.size() - 1);
}
}



