Created
July 15, 2014 02:19
-
-
Save chrislukkk/be1ffddf2aff327f33a8 to your computer and use it in GitHub Desktop.
Career cup 4.9 - Find all path sum to a value
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 Chapter4; | |
import java.util.LinkedList; | |
import java.util.List; | |
public class SumPathFinder { | |
private BinaryTree<Integer> tree; | |
public SumPathFinder(BinaryTree<Integer> t) { | |
tree = t; | |
} | |
public void printAllPath(int sum) { | |
getAllPath(sum, tree.root()); | |
} | |
public void getAllPath(int sum, TreeNode<Integer> node) { | |
if(node == null) return; | |
getSumPath(node, sum, new LinkedList<Integer>()); | |
getAllPath(sum, node.left); | |
getAllPath(sum, node.right); | |
} | |
public void getSumPath(TreeNode<Integer> node, int remain, | |
List<Integer> path) { | |
if (node == null) | |
return; | |
int value = node.key; | |
path.add(value); | |
if (remain == value) { | |
print(path); | |
} | |
//find all paths start from left nodes of current root | |
getSumPath(node.left, remain - value, path); | |
path.remove(path.size() - 1); | |
//find all paths start from right nodes of current root | |
path.add(node.key); | |
getSumPath(node.right, remain - value, path); | |
path.remove(path.size() - 1); | |
} | |
private void print(List<Integer> path) { | |
System.out.print("Path: "); | |
for (Integer key : path) { | |
System.out.print(key + "; "); | |
} | |
System.out.println(); | |
} | |
public static void main(String args[]) { | |
/* _______7______ | |
/ \ | |
__10__ ___14 | |
/ \ / | |
4 3 _-5 | |
\ / | |
1 12 */ | |
Integer[] pre = { 7, 10, 4, 3, 1, 14, -5, 12 }; | |
Integer[] in = { 4, 10, 3, 1, 7, 12, -5, 14 }; | |
BinaryTree<Integer> bt1 = BinaryTreeBuilder.buildTree(pre, in); | |
new SumPathFinder(bt1).printAllPath(21); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment