1357. 路径总和 II
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
样例
样例 1:
输入: root = {5,4,8,11,#,13,4,7,2,#,#,5,1}, sum = 22
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
输出: [[5,4,11,2],[5,8,4,5]]
解释:
两条路径之和为 22:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
样例 2:
输入: root = {10,6,7,5,2,1,8,#,9}, sum = 18
10
/ \
6 7
/ \ / \
5 2 1 8
\
9
输出: [[10,6,2],[10,7,1]]
解释:
两条路径之和为 18:
10 + 6 + 2 = 18
10 + 7 + 1 = 18
注意事项
叶子节点是指没有子节点的节点。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
List<List<Integer>> result=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
// Write your code here.
dfs(new ArrayList<Integer>(),root,sum,0);
return result;
}
private void dfs(List<Integer> integers, TreeNode root, int sum, int ret) {
if (root==null)return;
integers.add(root.val);
ret+=root.val;
if (ret>=sum) {
if (ret==sum)result.add(new ArrayList<>(integers));
integers.remove(integers.lastIndexOf(root.val));
return;
}
dfs(integers,root.left,sum,ret);
dfs(integers,root.right,sum,ret);
integers.remove(integers.lastIndexOf(root.val));
}
}
List<List<Integer>> result=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
// Write your code here.
dfs(new ArrayList<Integer>(),root,sum,0);
return result;
}
private void dfs(List<Integer> integers, TreeNode root, int sum, int ret) {
if (root==null)return;
integers.add(root.val);
ret+=root.val;
if (ret>=sum) {
if (ret==sum)result.add(new ArrayList<>(integers));
integers.remove(integers.size()-1);
return;
}
dfs(integers,root.left,sum,ret);
dfs(integers,root.right,sum,ret);
integers.remove(integers.size()-1);
}