原文:
You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.
译文:
给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
思路:
非常好的一题!时间复杂度:O(nlogn),空间复杂度:O(logn)
结合了回溯和另外一个重要思想!
就是下面的代码:在path数组里保存着当前的路径,以及当前的层level,然后我们可以由当前层往上遍历,看能不能凑到sum
// 统计从level(当前层)往上走,能否凑到sum
// 重要思想!
int t = 0;
for(int i=level; i>=0; i--) {
t += path[i];
if(t == sum) {
print(path, i, level); // i: start, level: end
}
}
下面是总的代码:
package Tree_Graph;
import CtCILibrary.TreeNode;
public class S4_9 {
public static void findSum(TreeNode root, int sum) {
int depth = depth(root);
int[] path = new int[depth]; // 建一个path数组,存放每一层的值
findSum(root, sum, path, 0);
}
// 递归打印所有可能
// path数组保存当前走过的路线,level表示当前到达的层
public static void findSum(TreeNode root, int sum, int[] path, int level) {
if(root == null){
return;
}
path[level] = root.data; // 先为当前层赋值
// 统计从level(当前层)往上走,能否凑到sum
// 重要思想!
int t = 0;
for(int i=level; i>=0; i--) {
t += path[i];
if(t == sum) {
print(path, i, level); // i: start, level: end
}
}
findSum(root.left, sum, path, level+1);
findSum(root.right, sum, path, level+1);
path[level] = Integer.MIN_VALUE; // 撤销当前层赋值
}
// 求高度
public static int depth(TreeNode root) {
if(root == null) {
return 0;
}
return 1 + Math.max(depth(root.left), depth(root.right));
}
public 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){
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(1);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(2);
root.right.right = new TreeNode(6);
findSum(root, 8);
}
}