您的位置:首页 > 其它

[leetCode刷题笔记]113. Path Sum II

2017-06-25 23:46 375 查看
/**
* 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>>();
List<Integer> path = new ArrayList<Integer>();
helper(root, sum, path, res);
return res;
}

private void helper (TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) {
if (root == null) {

return;
}

path.add(root.val);
if (root.left == null && root.right == null) {
if (sum == root.val) {
res.add(new ArrayList<Integer>(path));
}
path.remove(path.size() - 1);
return;
}
helper(root.left, sum - root.val, path, res);
helper(root.right, sum - root.val, path, res);
path.remove(path.size() - 1);
return;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: