
囧!
================================
import java.io.*;
import java.util.*;
class node{
int key;
node left;
node right;
node(int k){
key = k;
left = null;
right = null;
}
}
class BST{
node root;
BST(File f)throws FileNotFoundException{
build(f);
}
void build(File f)throws FileNotFoundException{
Scanner sr = new Scanner(f);
root = new node(sr.nextInt());
while(sr.hasNextInt()){
int k = sr.nextInt();
node p = null, r = root;
while(r!=null){
p = r;
r = k<r.key? r.left:r.right;
}
if(k<p.key)
p.left = new node(k);
else
p.right = new node(k);
//k<p.key? p.left=new node(k):p.right=new node(k);
}
sr.close();
}
public void infixTraverse(node t){
if(t==null)
return;
infixTraverse(t.left);
System.out.println(t.key+" ");
infixTraverse(t.right);
}
public boolean search(int k){
node r = root;
int count = 0;
boolean found = false;
while(!found && r!=null){
count++;
if(k==r.key){
found = true;
}else if(k<r.key){
r = r.left;
}else{
r = r.right;
}
System.out.print(count+" ");
}
return found;
}
}
public class BinarySearchTree{
public static void main(String[] alio)throws FileNotFoundException{
File f = new File("BinarySearchTreeText.txt");
BST bt = new BST(f);
bt.infixTraverse(bt.root);
System.out.println();
System.out.println(bt.search(32/*檔案中之資料搜尋*/));
System.out.println(bt.search(3));
}
}
================================
話說上面這台有支援雙打喔XD