LC.113.Path Sum II

https://leetcode.com/problems/path-sum-ii/description/
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]

难点:
1: 去哪里建一个LIST 不能每一次循环就建立一个NEW LIST: 我第一次做就是卡在这里了。
2: helper 返回值是否应该用一个BOOLEAN
3: 不用考虑走到一半不走了的情况,这道和 PATH SUM 一样,都是走到底:
root.left == null && root.right == null
4: ref 的特性: 1)new ArrayList<>(item) 2) 最后-1的原因


 1 public List<List<Integer>> pathSum(TreeNode root, int sum) {
 2         List<List<Integer>> res = new ArrayList<>() ;
 3         //corner case
 4         if (root == null) return res ;
 5         helper(root, sum, res, new ArrayList<>());
 6         return res;
 7     }
 8     /*
 9     需要一个 helper: boolean 只有当下面的返回上来,为TRUE 才把当前的结果加到 RES  中
10     * */
11     private void helper(TreeNode root, int sum, List<List<Integer>> res,List<Integer> pathRes){
12         //corner case: 走到底了
13         if (root == null) return ;
14         //PRE-ORDER
15         int newSum = sum - root.val ;
16         pathRes.add(root.val) ;
17         //判断sum是否为零并且当前的root 是否没有叶子了(已经走到底,不用再走了): 这道题是要走到底,不是走一半!
18         //如果 == 0 说明满足,放进PATH RES 然后返回
19         if (root.left == null && root.right == null &&newSum ==0 ){
20             //小心! pathRes IS REF type, 后面的如果对他进行修改,则会改变
21             res.add(new ArrayList<>(pathRes));
22             return;
23         }
24         //往下面走
25         if (root.left!=null){
26             helper(root.left, newSum, res, pathRes) ;
27             //重点处理! RECURSIVE 是一条道走到黑! 如果先走左边,走到最后一层层返回到这!
28             //因为你走完了左边 4-11(CURR)-7 现在要去 11的右边 4-11-2 并且用的又是同一个PATHRES,
29             //所以需要去掉 7 这个点 然后再去右边
30             pathRes.remove(pathRes.size()-1);
31         }
32         if (root.right != null){
33             helper(root.right,newSum, res, pathRes);
34             pathRes.remove(pathRes.size()-1);
35         }
36     }

 






转载于:https://www.cnblogs.com/davidnyc/p/8486587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值