Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created March 15, 2013 17:26
Show Gist options
  • Save Ray1988/5171567 to your computer and use it in GitHub Desktop.
Save Ray1988/5171567 to your computer and use it in GitHub Desktop.
given a tree, print out the path which contain together is a given number.
void findSum(TreeNode r, int sum){
int depth= depth(r);
int[] path=new int[depth];
int level=0;
findSum(r, path, sum, level);
}
public void findSum(TreeNode r, int[] path, int sum, int level){
if(r==null) return;
path[level]=r.data;
int t=0;
for(i=level; i>=0; i--){
t+=path[i];
if(t==sum){
print(path, i,level);
}
System.out.println();
}
findSum(r.left, path, sum, level+1);
findSum(r.right, path, sum, level+1);
}
public int depth(TreeNode r){
if(r==null) return 0;
return Math.max(depth(r.left), depth(r.right))+1;
}
public void print(int[] path, int start, int end){
if start< end return;
for(int i=start; i<=end; i++){
System.out.print(path[i]+" ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment