LeetCode Path Sum II
2015-09-07 04:14
295 查看
原题链接在这里:https://leetcode.com/problems/path-sum-ii/
递归调用,终止条件是当遇到叶子节点时判断sum是否为0,则res加当前ls. 若root.left 不为空,则ls.add(root.left.val)然后递归调用helper, 用完后要remove掉尾节点。右侧相同。
Note: 1. 当res加 ls时一定要res.add(new ArrayList(ls)), 因为list 是 pass by reference, 后面若更改ls, 则已经加到res里的ls也会同时更改。
2. 去掉list尾部就用ls.remove(ls.size()-1).
AC Java:
递归调用,终止条件是当遇到叶子节点时判断sum是否为0,则res加当前ls. 若root.left 不为空,则ls.add(root.left.val)然后递归调用helper, 用完后要remove掉尾节点。右侧相同。
Note: 1. 当res加 ls时一定要res.add(new ArrayList(ls)), 因为list 是 pass by reference, 后面若更改ls, 则已经加到res里的ls也会同时更改。
2. 去掉list尾部就用ls.remove(ls.size()-1).
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(root == null){ return res; } List<Integer> ls = new ArrayList<Integer>(); ls.add(root.val); helper(root,sum-root.val,res,ls); return res; } private void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> ls){ if(root.left == null && root.right == null && sum == 0){ res.add(new ArrayList(ls)); //error return; } if(root.left != null){ ls.add(root.left.val); helper(root.left,sum-root.left.val,res,ls); ls.remove(ls.size()-1); } if(root.right != null){ ls.add(root.right.val); helper(root.right,sum-root.right.val,res,ls); ls.remove(ls.size()-1); } } }
相关文章推荐
- LeetCode Path Sum II
- Ubuntu12.04下Qt5.2编译使用webkit程序 cannot find -lxslt gio-2.0 gstapp-0.10
- C#的正则表达式
- Linux命令帮助的获取
- Linux运维历史和计算机基础
- 实现Jquery触发一事件后,停留5秒,再接着触发下面的事件
- servlet/filter/listener/interceptor区别与联系
- Eclipse与Git结合使用
- NAT-PT原理与配置
- bzoj 2154 莫比乌斯反演求lcm的和
- 数据采集
- 伟大是熬出来的
- 在服务器上排除问题的头五分钟
- jdk各版本区别
- cocos植物大战僵尸(三)游戏场景:地图滚动
- 关于集成学习基础的简单描述
- 规则化和模型选择(Regularization and model selection)
- Linux文件系统上的特殊权限(SUID、SGID、Sticky)
- bash的变量
- find的使用方法