Monday, August 17, 2015

[Leetcode] [DFS]Path Sum II

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]
]
/*
Time:O(n), Space:O(k*logn), where k means total k 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> pathSum(TreeNode root, int sum) {
        List> res = new ArrayList>();
        // special case
        if ( root == null )
        {
            return res;
        }
        List item = new ArrayList();
        item.add(root.val);
        helper(root, sum - root.val, item, res);
        return res;
    }
    
    private void helper(TreeNode root, int sum, List item, List> res)
    {
        // leaf.left
        if (root == null )
        {
            return;
        }
        if ( root.left == null && root.right == null && sum == 0 ) // base case
        {
            //**** need a new one
            //res.add(item);
            res.add( new ArrayList(item) );
            return;
        }
        //  1
        // 2 3
        if ( root.left != null )
        {
            // 1 +2 
            item.add(root.left.val);
            helper(root.left, sum - root.left.val, item, res);
            // **** become 1 for 1+3
            item.remove(item.size()-1);
        }
        if ( root.right != null )
        {
            // 1+3
            item.add(root.right.val);
            helper(root.right, sum - root.right.val, item, res);
            // 1
            item.remove(item.size() -1);
        }
        return;
    }
}

No comments:

Post a Comment