您的位置:首页 > 其它

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:

/**
* 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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: