We use DFS to traverse the tree.

For each node through the path, let sum = sum - node.val.

When we look through a node, create a List<List<Integer>> to store the possible list result.

When we reach to its the leaf node then, if sum == node.val, create a new list to add the value, and add the list to retList. Otherwise, just return an empty list retList.

When we traverse a node before the leaf node, we have the following 3 cases:

Only left child exists, then get the retlist of the child, and for each list of the retlist, add(0, node,val) then return retlist;

Only right child exists, almost the same story of case 1.

Both left child and right child exist. First, we do the same operations in case1, then traverse the retlist of right child, get each list, and add(0, node.val), then add the list to the retlist we obtained in first step. Return it.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<Integer> list = new ArrayList<>(); 
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> retList = new ArrayList<>();
        if(root == null) return retList;
        List<Integer> list = new ArrayList<>();
        return addPathList(root, root, sum);
    }
    
    public List<List<Integer>> addPathList(TreeNode node, TreeNode root, int sum){
        List<List<Integer>> retList = new ArrayList<>();
        if(node.left == null && node.right == null){
            if(node.val != sum) return retList;
            list = new ArrayList<>();
            list.add(0, node.val);
            retList.add(list);
            return retList;
        }
        else if(node.left != null && node.right == null) {
            retList = addPathList(node.left, root, sum-node.val);
            for(int i = 0; i < retList.size(); i++){
                retList.get(i).add(0, node.val);
            }
            return retList;
        }
        else if(node.left == null && node.right != null) {
            retList = addPathList(node.right, root, sum-node.val);
            for(int i = 0; i < retList.size(); i++){
                retList.get(i).add(0, node.val);
            }
            return retList;
        }
        else{
            retList = addPathList(node.left, root, sum-node.val);
            for(int i = 0; i < retList.size(); i++){
                retList.get(i).add(0, node.val);
            }
            List<List<Integer>> rightList = 
                    addPathList(node.right, root, sum-node.val);
            for(int i = 0; i <rightList.size(); i++){
                List<Integer> l = new ArrayList<>();
                l = rightList.get(i);
                l.add(0, node.val);
                retList.add(l);
            }
            return retList;
        }
    }
    
}

 

posted on 2016-01-29 14:21  爱推理的骑士  阅读(129)  评论(0编辑  收藏  举报