平衡二叉树自己看书上定义。
直接上源码
若方法没写全,后续会补上。
public class BTS<Key extends Comparable<Key>,Value> {
private class Node
{
private Key key;
//键,用于比较,用Comparable类的子类来进行比较
private Value val;
//值
private Node left;
private Node right;
private int N;
//根结点数
public Node(Key key,Value val,int N)
{
this.key=key;
this.N=N;
this.val=val;
}
}
private Node root;
public int size()
{
return size(root);
}
private int size(Node x)
{
if(x==null)return 0;
else return x.N;
}
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.val;
}
public void put(Key key,Value val)
{//查找key,找到则更新它,否则为它创造一个新的结点
root = put(root,key,val);
}
private Node put(Node x,Key key,Value val)
{
if(x==null)return new Node(key,val,1);
int cmp = key.compareTo(x.key);
if (cmp<0)x.left = put(x.left,key,val);
else if(cmp>0)x.right=put(x.right,key,val);
else x.val=val;
x.N=size(x.left)+size(x.right)+1;
return x;
}
public Key min(){
return min(root).key;
}
private Node min(Node x){
if(x.left==null)return x;
return min(x.left);
}
/*找到比key小的值中最大的那一个*/
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) return null;
else 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;
/*
1.若相等直接返回
2.若key的值较小,先去左边找,没有返回null
3.若key较大,去右边比较,重复1,2,3操作
逐级返回
若向右找后,找不到更小的,返回x
找到则返回t
celeing思想相同
*/
}
public Key max(){
return max(root).key;
}
private Node max(Node x){
if(x.right==null)return x;
return max(x.right);
}
/*找到比key大的值中最小的那一个*/
public Key ceiling(Key key){
Node x = ceiling(root,key);
if(x==null)return null;
return x.key;
}
private Node ceiling(Node x,Key key){
if(x==null)return null;
int cmp=key.compareTo(x.key);
if(cmp==0)return x;
if(cmp>0)return ceiling(x.right,key);
Node t = ceiling(x.left,key);
if(t!=null)return t;
else 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.right)+size(x.left)+1;
return x;
}
public void deleteMax(){
root=deleteMax(root);
}
private Node deleteMax(Node x)
{
if(x.right==null)return x.left;
x.right=deleteMax(x.right);
x.N=size(x.right)+size(x.left)+1;
return x;
}
public void delete(Key key)
{
root = delete(root,key);
}
private Node delete(Node x,Key key)
{
if(x==null)return null;
int cmp = key.compareTo(x.key);
if (cmp<0)return delete(x.left,key);
else if(cmp>0)return delete(x.right,key);
else {
if(x.right==null)return x.left;
if(x.left==null)return x.right;
Node t = x;
x = min(t.right);
x.right=deleteMin(t.right);
x.left=t.left;
}
x.N=size(x.left)+size(x.right)+1;
return x;
}
}
1490





