LeetCode 113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
the follow up the LC112.
but the difference is: LC112 ask if we can find some path like that then return true.
and this problem needs us to return all the path that equals to sum.
费了半天劲 终于鼓捣出来一个 但是输出来的却不对 每个元素重复了两遍。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
helper(root, res, new ArrayList<>(), sum, 0);
return res;
}
private void helper(TreeNode root, List<List<Integer>> res, List<Integer> list, int sum, int target) {
if (root == null) {
if (sum == target) {
res.add(new ArrayList<>(list));
}
return;
}
list.add(root.val);
helper(root.left, res, list, sum, target + root.val);
helper(root.right, res, list, sum, target + root.val);
list.remove(list.size() - 1); //backtracking
}
}
输出:[[5,4,11,2],[5,4,11,2],[5,8,4,5],[5,8,4,5]]
正确的应该是下面这个:
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
helper(root, res, new ArrayList<>(), sum, 0);
return res;
}
private void helper(TreeNode root, List<List<Integer>> res, List<Integer> list, int sum, int target) {
if (root == null) return;
list.add(root.val);
if (root.left == null && root.right == null) {
if (sum == target + root.val) {
res.add(new ArrayList<>(list)); //copy一个副本
}
}
helper(root.left, res, list, sum, target + root.val);
helper(root.right, res, list, sum, target + root.val);
list.remove(list.size() - 1);
}
}
不过我也并没有看出之前的代码的有什么问题 不过有几个地方是需要用力注意一下:
首先就是root == null的特殊情况处理 一定要处理
第二个是上述代码是backtracking的最好体现 要想明白了
第三个就是要节点是叶子节点做特殊处理 因为者代表一个路径走到头了

浙公网安备 33010602011771号