题目:在二叉树中查找值为X的结点,试设计打印值为X的结点的所有祖先的算法,假设值为X的结点不多于1个。
import java.util.*;
public class BinTree {
private List binTree;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int node;
System.out.println("Build binary tree.");
System.out.println("Enter number of tree node: ");
int n = reader.nextInt();
BinTree bt = new BinTree(n);
System.out.println("Enter the " + n + " tree nodes");
for (int i = 0; i < n; i++) {
node = reader.nextInt();
bt.addNode(node);
}
System.out.println("Enter the vaule X to find:");
int target = reader.nextInt();
if (bt.find(target)) {
bt.printParentsOf(target);
}
else
System.out.println("Can't find " + target);
}
public boolean find(int t) {
return binTree.contains(t);
}
public void printParentsOf(int target) {
int index = binTree.indexOf(target);
if (index != 1)
printParentsOf(binTree.get(index/2));
System.out.println(binTree.get(index));
}
public BinTree(int n) {
binTree = new ArrayList(n);
binTree.add(0, -1); // 占位
}
public void addNode(int node) {
binTree.add(node);
}
}