Saturday, February 15, 2014

Path Sum II @LeetCode


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

package leetcode.combinations;
import java.util.ArrayList;
/**
* Solution: DFS Traversal + Combination
* Use sum with traversal to implement to target -- What I think is use another sum += root.val, but obviously,
* it's more complicated than sum -= root.val;
*
* @author jeffwan
* @date Feb 15, 2014
*/
public class PathSum {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
helper(result, list, root, sum);
return result;
}
private void helper(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> list, TreeNode root, int sum) {
if (root == null) {
return;
}
sum -= root.val;
if (root.left == null && root.right == null) {
if (sum == 0) {
list.add(root.val);
result.add(new ArrayList<Integer>(list));
list.remove(list.size() - 1);
}
return;
}
list.add(root.val);
helper(result, list, root.left, sum);
helper(result, list, root.right, sum);
list.remove(list.size() - 1);
}
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { this.val = x; }
}
}
view raw pathSum.java hosted with ❤ by GitHub

No comments:

Post a Comment