Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created July 21, 2014 17:16
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 bitcpf/8beb7c1e035c08461596 to your computer and use it in GitHub Desktop.
Save bitcpf/8beb7c1e035c08461596 to your computer and use it in GitHub Desktop.
package cc150_4_9;
import java.util.LinkedList;
import cc150_4_9.BinaryTree.Node;
public class CheckSum {
private BinaryTree tree;
public CheckSum(BinaryTree t){
tree = t;
}
public void printAllPath(int sum){
getAllPath(sum,tree.root);
}
private void getAllPath(int sum, Node root) {
// TODO Auto-generated method stub
if(root == null) return;
int val = (Integer) root.key;
getSumPath(root,sum,new LinkedList<Integer>());
getAllPath(sum,root.left);
getAllPath(sum,root.right);
}
private void getSumPath(Node root, int sum, LinkedList<Integer> path) {
// TODO Auto-generated method stub
if(root == null) return;
int val = (Integer) root.key;
path.add(val);
if(sum == val){
print(path);
}
getSumPath(root.left,sum - val,path);
path.remove(path.size()-1);
path.add((Integer) root.key);
getSumPath(root.right,sum - val,path);
path.remove(path.size()-1);
}
private void print(LinkedList<Integer> path) {
// TODO Auto-generated method stub
System.out.print("Path: ");
for (Integer key : path) {
System.out.print(key + "; ");
}
System.out.println();
}
public static void main(String[] args){
Integer[] pre = { 7, 10, 4, 3, 1, 14, -5, 12 };
BinaryTree test = new BinaryTree(pre);
test.printTree(test.root);
System.out.println();
System.out.println(test.root.key);
new CheckSum(test).printAllPath(3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment