*LeetCode-Path Sum II

和以前做的backtracking很像 但是注意要删除这次add的node!!否则左边recurse加上了left 到了右边却没有remove left就继续了

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>> ();
        List<Integer> list = new ArrayList<Integer> ();
        helper ( res, list, root, sum );
        return res;
    }
    public void helper ( List<List<Integer>> res, List<Integer> list, TreeNode root, int sum ){
        if ( root == null )
            return;
        list.add ( root.val );
        if ( root.val == sum && root.left == null && root.right == null ){
            res.add ( new LinkedList (list) );
            list.remove( list.size() - 1 );
            return;
        }
        helper ( res, list, root.left, sum - root.val );
        helper ( res, list, root.right, sum - root.val );
        list.remove( list.size() - 1 );
    }
}


你可能感兴趣的:(*LeetCode-Path Sum II)