Created
March 15, 2013 17:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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