您的位置:首页 > 其它

113. Path Sum II

2017-09-22 00:00 232 查看
一定要记住每次走到最后要把path最后一个Node删除

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {

List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(root, sum, res, path);
return res;
}

public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path){
if (root == null){
return;
}
//add current node into list
path.add(new Integer(root.val));

if (root.left == null && root.right == null && root.val == sum){
res.add(new ArrayList<Integer>(path));
return;
}

if(root.left != null){
helper(root.left, sum-root.val, res, path);
path.remove(path.size()-1);
}
if(root.right != null){
helper(root.right, sum-root.val, res, path);
path.remove(path.size()-1);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: