Wednesday, March 20, 2013

Path Sum II


Given a binary tree and a sum, find all root-to-leaf paths where each paths 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]
]
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

traverse the whole tree, then we get the answer.

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> ret;
    ArrayList<Integer> tran;
    void buildPath(TreeNode root, int sum){
        if(root.left == null && root.right == null){
            if(sum == root.val){
                ArrayList<Integer> n = new ArrayList<Integer>(tran);
                n.add(root.val);
                ret.add(n);
            }
            return;
        }
        tran.add(root.val);
        if(root.left != null) buildPath(root.left,sum - root.val);
        if(root.right != null) buildPath(root.right, sum - root.val);
        tran.remove(tran.size()-1);
    }
   
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ret = new ArrayList<ArrayList<Integer>>();
        tran = new ArrayList<Integer>();
        if(root == null) return ret;
        buildPath(root, sum);
        return ret;
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/