请再接再厉!
public class test
{
public static void main(String[] args)
{
BST<Integer,Integer> a=new BST();
a.put(10, 9);
a.put(20, 19);
a.put(6, 5);
System.out.println(a.floor(18));
}
}
class BST<KEY extends Comparable<KEY>,VALUE>
{
private Node root;
class Node
{
KEY key;
VALUE value;
Node left,right;
int N;//数量
public Node(KEY key,VALUE value,int N)
{this.key=key;this.value=value;this.N=N;}
}
public int size(){return size(root);}
private int size(Node x)
{
if(x==null)return 0;
return x.N;
}
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);//设置root为空时
int cmp=key.compareTo(x.key);
if(cmp<0)x.left=put(x.left, key, value);
else if(cmp>0)x.right=put(x.right, key, value);
else x.value=value;
x.N=size(x.left)+size(x.right)+1;
return x;
}
public VALUE get(KEY key){return get(root,key);}
private VALUE get(Node x,KEY key)
{
if(x==null)return null;
int cmp=key.compareTo(x.key);
if(cmp<0)return get(x.left,key);
else if(cmp>0)return get(x.right,key);
else return x.value;
}
public KEY floor(KEY key)
{
Node x=floor(root,key);
if(x==null)return null;
return x.key;
}
private Node floor(Node x,KEY key)
{
if(x==null)return null;
int cmp=key.compareTo(x.key);
if(cmp==0)return x;
if(cmp<0)return floor(x.left, key);
Node t=floor(x.right, key);
if(t!=null)return t;
else return x;
}
}
``