题目描述:输入一棵二叉树和一个整数, 打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
题目分析:由于路径是从根节点出发到叶子结点,也就是说路径总是以根结点为起点,因此我们首先需要遍历根节点。在树的前序遍历后序遍历和中序遍历中只有前序遍历是先访问根节点的。
当前序遍历访问到某一结点时,我们把该结点添加到路径上,并累加该结点的值,如果该结点为叶子结点并且路径中结点值的和刚好等于输入的整数,则当前路径符合要求,我们把它打印出来,如果当前结点不是叶子结点,则继续访问它的子结点,当前结点访问结束后,递归函数将自动回到它的父结点,因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父节点时路径刚好是从根结点到父结点的路径。可以看出,保存路径的数据结构就是一个栈。
public static void findBTSPath(BinaryTreeNode root, int currentSum, int sum, Stack<Integer> stack) {
if (root != null) {
currentSum = currentSum + root.value;
stack.push(root.value);
if (currentSum < sum) {
findBTSPath(root.left,currentSum,sum,stack);
findBTSPath(root.right,currentSum,sum,stack);
}else if(currentSum == sum){
return;
}else{
stack.pop();
}
}
}
public static void findPath(BinaryTreeNode root, int sum) {
Stack<Integer> list = new Stack<>();
if (root != null) {
findBTSPath(root, 0, sum, list);
}
}