import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class Tree{
int v;
Tree left;
Tree right;
}
public class PathofTree {
//从数组中递归创建树,i 数组中的第i个元素,返回树的根节点
public static Tree creat(int [] data,int i){
if(data==null || i<0||i>=data.length){
return null;
}else{
Tree root = new Tree();
root.v=data[i];
root.left=creat(data, (i<<1)+1);
root.right=creat(data, (i<<1)+2);
return root;
}
}
//按层次遍历树 root树的根节点
public static void levelPrintTree(Tree root){
if(root==null){
return;
}
Queue<Tree> queue=new LinkedList<Tree>();
queue.add(root);
while(!queue.isEmpty()){
Tree node = queue.poll();
System.out.print(node.v+"\t");
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
System.out.println();
}
//查找二叉树中和为某一值的路径
public static void findPath(Tree root,int expectSum,Stack<Integer> stack,
int currentSum){
if(root==null){
return;
}
stack.push(root.v);
currentSum+=root.v;
//如果是叶子节点,而且和为给定值,则打印路径
boolean isleaf=root.left==null && root.right==null;
if(isleaf && currentSum==expectSum){
for(Integer e:stack){
System.out.print(e+"\t");
}
System.out.println();
}
//如果不是叶子节点,则遍历它的子节点
if(root.left!=null){
findPath(root.left, expectSum, stack, currentSum);
}
if(root.right!=null){
findPath(root.right, expectSum, stack, currentSum);
}
stack.pop();
}
public static void main(String[] args) {
int data[]={10,5,12,4,7};
Tree rootTree=creat(data, 0);
levelPrintTree(rootTree);
Stack<Integer> stack=new Stack<Integer>();
findPath(rootTree, 22, stack, 0);
}
}