基于二叉查找树的符号表
public class BST <Key extends Comparable<Key>,Value>{
private Node root;
private class Node{
private Key key;
private Value value;
private Node left;
private Node right;
private int n;
public Node(Key key, Value value, int n) {
this.key = key;
this.value = value;
this.n = n;
}
}
public Value get(Key key){
return get(root, key);
}
private Value get(Node x,Key key){
if (x == null)
return null;
int res = key.compareTo(x.key);
if(res==0){
return x.value;
}
else if(res<0)
return get(x.left,key);
else
return get(x.right,key);
}
public void put(Key key,Value value){
root=put(root,key,value);
}
private Node put(Node x,Key key,Value value){
if(x==null)
return new Node(key,value,1);
int res = key.compareTo(x.key);
if(res==0){
x.value=value;
}
else if(res<0)
x.left=put(x.left,key,value);
else
x.right=put(x.right,key,value);
x.n=size(x.left)+size(x.right)+1;
return x;
}
public void delete(Key key){
root = delete(this.root, key);
}
private Node delete(Node x,Key key){
if(x==null)
return null;
int t = key.compareTo(x.key);
if (t<0)
x.left=delete(x.left,key);
else if(t>0)
x.right=delete(x.right,key);
else {
if(x.left==null)
return x.right;
if(x.right==null)
return x.left;
Node tt= x;
x=min(tt.right);
x.right=deleteMin(tt.right);
x.left=tt.left;
}
x.n=size(x.left)+size(x.right)+1;
return x;
}
public void deleteMin(){
root=deleteMin(root);
}
private Node deleteMin(Node x){
if(x.left==null){
return x.right;
}
x.left=deleteMin(x.left);
x.n=size(x.left)+size(x.right)+1;
return x;
}
public int size(){
return size(root);
}
private int size(Node x){
if(x==null)
return 0;
else
return x.n;
}
public Key min(){
return min(root).key;
}
private Node min(Node x){
if(x.left==null)
return x;
return min(x.left);
}
public Key select(int k){
return select(root,k).key;
}
private Node select(Node x,int k){
if(x==null){
return null;
}
int t =size(x.left);
if(t>k)
return select(x.left,k);
else if(t<k)
return select(x.right,k-t-1);
else
return x;
}
}