前言
??????用Java简单的实现二叉查找树。
import java.nio.BufferUnderflowException;
import java.util.ArrayDeque;
public class BinarySearchTree<T extends Comparable<? super T>>{
private static class BinaryNode<T> {
T element;
BinaryNode<T> left;
BinaryNode<T> right;
public BinaryNode(T a){
element=a;
left=right=null;
}
public BinaryNode(T a, BinaryNode<T> le, BinaryNode<T> ri){
element=a;
left=le;
right=ri;
}
}
private BinaryNode<T> root;
public BinarySearchTree(){
root=null;
}
public boolean isEmpty(){
return root==null;
}
public void makeEmpty(){
root=null;
}
public boolean contains(T element){
return contains(element,root);
}
private boolean contains(T element,BinaryNode<T> root){
if(root==null)
return false;
if(element.compareTo(root.element)==0)
return true;
if(element.compareTo(root.element)<0)
return contains(element,root.left);
else
return contains(element,root.right);
}
public T findMin(){
if(isEmpty())
throw new BufferUnderflowException();
return findMin(root);
}
private T findMin(BinaryNode<T> root){
while(root.left!=null)
root=root.left;
return root.element;
}
public T findMax(){
if(isEmpty())
throw new BufferUnderflowException();
return findMax(root);
}
private T findMax(BinaryNode<T> root){
if(root.right==null)
return root.element;
return findMax(root.right);
}
public void insert(T element){
root=insert(element,root);
}
private BinaryNode<T> insert(T element,BinaryNode<T> root){
if(root==null)
return new BinaryNode<T>(element);
int compareRe=element.compareTo(root.element);
if(compareRe<0)
root.left=insert(element,root.left);
else if(compareRe>0)
root.right=insert(element,root.right);
else
;
return root;
}
public void remove(T element){
root=remove(element,root);
}
private BinaryNode<T> remove(T element,BinaryNode<T> root){
if(root==null)
return root;
int compareRe=element.compareTo(root.element);
if(compareRe<0)
root.left=remove(element,root.left);
else if(compareRe>0)
root.right=remove(element,root.right);
else if(root.left!=null&&root.right!=null){
root.element=findMax(root.right);
root.right=remove(root.element,root.right);
}
else
root=(root.right==null)?root.left:root.right;
return root;
}
public void printTree(){
if(root==null)
return;
ArrayDeque<BinaryNode<T>> queue=new ArrayDeque<>();
queue.offerLast(root);
int remainingNode=1,nextLayerN=0;
while(!queue.isEmpty()){
BinaryNode<T> tmp=queue.pollFirst();
System.out.print(tmp.element+" ");
remainingNode--;
if(tmp.left!=null){
queue.offerLast(tmp.left);
nextLayerN++;
}
if(tmp.right!=null){
queue.offerLast(tmp.right);
nextLayerN++;
}
if(remainingNode==0){
System.out.println();
remainingNode=nextLayerN;
nextLayerN=0;
}
}
}
public static void main(String[] args){
}
}
|