题目
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径。
思路
- 前序遍历二叉树,并用一个栈stack来存储路径,用一个变量sumPath存储路径之和;每当前序遍历从子结点返回父节点时,弹出该子结点,并且sumPath减去该结点的值;
- findPath(BiTreeNode root,int expectedSum)创建变量sumPath和结点栈stack;
- findPath(BiTreeNode current,int expectedSum,Stack stack,int sumPath)为主要的递归过程;首先将current的值加入sumPath,并压入stack,当为叶节点时判断当前路径sumPath是否等于expectedSum;如果不是叶结点,当current结点的左子结点不为null,递归调用,右子结点同理,注意java函数为复制一个引用传递变量值,所以不同递归深度的sumPath值不同,不用刻意在弹出某个结点时,sumPath减去该值;
- 从子结点返回父节点的过程,需要弹出子结点。
- 在这里,由于要在不改变栈结构的情况下遍历栈,所以没有采用自己定义的栈,而采用java.util.Stack。
import datastructure.search.BiTreeNode;
import java.util.Stack;
public class Q25FindPath {
public static void findPath(BiTreeNode root,int expectedSum){
if (root==null)
return;
int sumPath=0;
Stack<Integer> stack=new Stack<Integer>();
findPath(root,expectedSum,stack,sumPath);
}
public static void findPath(BiTreeNode current,int expectedSum,Stack<Integer> stack,int sumPath){
sumPath+=current.data;
stack.push(current.data);
boolean isLeaf=current.leftChild==null&¤t.rightChild==null;
if (isLeaf&&sumPath==expectedSum){
System.out.println("----------A new path found:----------");
for (int i:stack)
System.out.print(i+" ");
System.out.println("\n");
}else {
if (current.leftChild != null) {
findPath(current.leftChild, expectedSum, stack, sumPath);
}
if (current.rightChild!=null){
findPath(current.rightChild,expectedSum,stack,sumPath);
}
}
stack.pop();
}
public static void main(String[] args) {
int[] array={10,5,12,4,7};
BiTreeNode root=BiTreeNode.create(array);
findPath(root,22);
}
}