您的位置:首页 > 其它

Path Sum II

2015-06-03 11:58 344 查看
Path Sum II 

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]
]

 The path sum needs us to return a boolean whereas this problem wants us to return all the possible paths. Using DFS to list all the possible paths.

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