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;
}
}
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
No comments:
Post a Comment