题解 | #二叉树中和为某一值的路径(二)#(阿飞算法)
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
JZ34 二叉树中和为某一值的路径(二)
方法1:回溯-递减
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int targetSum) {
dfs(root, targetSum, new ArrayList<>());
return res;
}
private void dfs(TreeNode root, int sum, ArrayList<Integer> sub) {
if (root == null) {
return;
}
sub.add(root.val);
if (root.left == null && root.right == null && sum == root.val) res.add(new ArrayList<>(sub));
dfs(root.left, sum - root.val, sub);
dfs(root.right, sum - root.val, sub);
sub.remove(sub.size() - 1);
}
方法2:回溯-累加
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int sum) {
if (root == null) return res;
dfs(root,sum,0,new ArrayList<>());
return res;
}
private void dfs(TreeNode root, int sum, int total, ArrayList<Integer> sub) {
if (root == null) return;
sub.add(root.val);
total += root.val;
if (root.left == null && root.right == null) {
if (sum == total) {
res.add(new ArrayList<>(sub));
}
//这一步是为了移除这个叶子节点的值,不管这个叶子节点是否满足条件
sub.remove(sub.size() - 1);
return;
}
dfs(root.left, sum, total, sub);
dfs(root.right, sum, total, sub);
sub.remove(sub.size() - 1);
}