Topic 4.9 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. Note that a path can start or end anywhere in the tree.
//路径被存在一个数组里
public class c4_9 {
public static void findSum(TreeNode node, int sum, int[] path, int level) {
if (node == null) {
return;
}
/* Insert current node into path */
path[level] = node.data; //树还是从上往下加,把每条路径放在path里(每找一个sum,都是从第一层往最后一层,找个遍,是很麻烦
int t = 0;
for (int i = level; i >= 0; i--){//这里的时候,把path从后往前加,等于sum就打印
t += path[i];
if (t == sum) {
print(path, i, level);
}
}
findSum(node.left, sum, path, level + 1);
findSum(node.right, sum, path, level + 1);
}
//返回一棵树的深度,从1开始数
public static int depth(TreeNode node) {
if (node == null) {
return 0;
} else {
return 1 + Math.max(depth(node.left), depth(node.right));
}
}
public static void findSum(TreeNode node, int sum) {
int depth = depth(node);
int[] path = new int[depth];
findSum(node, sum, path, 0);
}
private static void print(int[] path, int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(path[i] + " ");
}
System.out.println();
}
public static void main(String [] args){
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode root = TreeNode.createMinimalBST(array);
findSum(root, 8);
}
}
//结果
5 2 1
8