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);
}
}