-
-
Save bitcpf/8beb7c1e035c08461596 to your computer and use it in GitHub Desktop.
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
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