二叉查找树的性质是,对于树中的每个节点X,它的左子树中的所有项的值都小于X中的项,而右子树相反。这样只需递归的比较两项的大小便可很容易的从树内查找出所需元素。通过实现Comparable接口的compareTo方法来对两项进行比较。
一个节点代表其与其的后代节点构成的树,根节点代表整棵树。
页面卡死两次!!白打了太多!!学校10点断网!!注释不重新加了!!!
public class BinarySearchTree>{
private static class BinaryNode{
AnyType element;
BinaryNode left;
BinaryNode right;
BinaryNode(AnyType theElement){
this(theElement,null,null);
}
BinaryNode(AnyType theElement,BinaryNode lt,BinaryNode rt){
element = theElement;
left = lt;
right = rt;
}
}
private BinaryNode root;
public BinarySearchTree(){
root = null;
}
public void makeEmpty(){
root = null;
}
public boolean isEmpty(){
return root == null;
}
public boolean contains(AnyType x){
return contains(x,root);
}
public AnyType findMin(){
if(isEmpty()) throw new UnderflowException();
return findMin(root).element;
}
public AnyType findMax(){
if(isEmpty()) throw new UnderflowException();
return findMax(root).element;
}
public void insert(AnyType){
root = insert(x,root);
}
publci void remove(AnyType x){
root = remove(x,root);
}
public void printTree(){
if(isEmpty())
sysout("Empty Tree");
else
printTree(root);
}
private void printTree(BinaryNode t){
if(t!=null){
printTree(t.left);
sysout(t.element);
printTree(t.right);
}
}
public boolean contains(AnyType x,BinaryNode t){
if(t==null)
return false;
int compareResult = x.compareTo(t.element);
if(compareResult<0)
return contains(x,t.left);
else if(compareResult>0)
return contains(x,t,right);
else
return true;
}
private BianryNode findMin(BianryNode t){
if(t==null)
return null;
else if(t.left==null)
return t;
return findMin(t.left);
}
private BianryNode findMax(BianryNode t){
if(t!=null)
while(t.right!=ull)
t = t.right;
return t;
}
public BianryNode insert(AnyType x,BinaryNode t){
if(t==null)
return new BinaryNode(x,null,null);
int compareResult = x.compareTo(t.element);
if(compareResult<0)
t.left = insert(x,t.left);
else if(compareResult>0)
t.right = insert(x,t.right);
else ;
return t;
}
public BianryNode remove(AnyType x,BinaryNode t){
if(t==null)
return t;
int compareResult = x.compareTo(t.element);
if(compareResult<0)
t.left = remove(x,t.left);
else if(compareResult>0)
t.right = remove(x,t.right);
else if(t.left!=null && t.right !=null){
t.element = findMin(t.right).element;
t.right = remove(t.element,t.right);
}
else
t = (t.left !=null) ? t.left:t.right;
return t;
}
}