Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyhjuzi/6e9670d8ab016343cc07 to your computer and use it in GitHub Desktop.
Save jyhjuzi/6e9670d8ab016343cc07 to your computer and use it in GitHub Desktop.
public class Q4_9{
public static void main(String[] args){
int[] array = { 1,2,3,7,5,-6,-4,8,3,-2,5,4 };
TreeNode<Integer> root1 = new Q4_3().arrayToBST(array, 0, 11);
/* -6
/ \
3 3
/ \ / \
1 7 -4 5
\ \ \ /\
2 5 8 -2 4*/
int[] path = new int[10];
checkSum(root1,0,path,0);
}
public static void checkSum(TreeNode<Integer> node, int sum, int[] path, int level){
if(node == null)
return;
path[level]=node.value;
getPaths(sum,path,level);
checkSum(node.left, sum,path,level+1);
checkSum(node.right,sum,path,level+1);
}
static void getPaths(int target,int[] path, int level){
int sum = 0;
int end = level;
int start = 0;
for(int i = level; i>=0;i--){
sum = sum+path[i];
if(sum==target){
start=i;
printPath(path,start,end);
}
}
}
static void printPath(int[] path, int start, int end){
System.out.println("Path: ");
for(int i = start; i<= end; i ++){
System.out.print(path[i]+" ");
}
System.out.println("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment