BiruLyu
5/30/2017 - 2:55 AM

113. Path Sum II.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>>();
        List<Integer> solution = new ArrayList<Integer>();
        if(root == null) return res;
        dfs(root, sum, solution, res);
        return res;
    }
    
    public void dfs(TreeNode root, int sum, List<Integer> solution, List<List<Integer>> res){
        //if(root == null) return;

        solution.add(root.val);
        sum -= root.val;
        if(root.left == null && root.right == null && sum == 0) {
            res.add(new ArrayList(solution));
            solution.remove(solution.size() - 1);
            sum += root.val;
            return;
        }
        if(root.left != null) {
            dfs(root.left, sum, solution, res);
        }
        if(root.right != null) {
            dfs(root.right, sum, solution, res);
        }
        solution.remove(solution.size() - 1);
        sum += root.val;
        
    }
}