Tuesday, June 3, 2014

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

Solution:

/**
 * Definition for binary tree
 * 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>> solution = new ArrayList<List<Integer>>();
        pathSum(root, sum, 0, new ArrayList<Integer>(), solution);
        return solution;
    }
    
    public void pathSum(TreeNode root, int target, int tempSum, ArrayList<Integer> tempSolution, List<List<Integer>> solution)
    {
        if(root == null)
            return;
        tempSolution.add(root.val);
        tempSum+= root.val;
        if(root.left == null && root.right == null)
        {
            if(tempSum == target)
                solution.add((List<Integer>) tempSolution.clone());
            
        }
        else
        {
            pathSum(root.left, target, tempSum, tempSolution, solution);
            pathSum(root.right, target, tempSum, tempSolution, solution); 
        }
        tempSolution.remove(tempSolution.size()-1);
    }
}

No comments :

Post a Comment