红黑树

红黑树

import sun.applet.Main;

import java.util.Base64;

public class RedBlackBST <Key extends Comparable<Key>,Value> {
    private class Node{
        Key key;
        Value value;
        Node left,right;
        int n;
        boolean color;

        public Node(Key key, Value value, int n, boolean color) {
            this.key = key;
            this.value = value;
            this.n = n;
            this.color = color;
        }
    }
    private static final boolean Red =true;
    private static final boolean Black = false;

    private Node root;

    private boolean isRed(Node x){
        if(x==null)
            return false;
        return x.color==Red;
    }

    private Node rotateLeft(Node h){   //左旋
        Node x =h.right;
        h.right=x.left;
        x.left=h;
        x.color=h.color;
        h.color=Red;
        x.n=h.n;
        h.n=1+size(h.right)+size(h.left);
        return x;  //返回根节点
    }


    private Node rotateRight(Node h){   //右旋
        Node x =h.left;
        h.left=x.right;
        x.right=h;
        x.color=h.color;
        h.color=Red;
        x.n=h.n;
        h.n=1+size(h.right)+size(h.left);
        return x;  //返回根节点
    }

    private int size(Node x){
        if(x==null)
            return 0;
        return x.n;
    }

    private void flipColors(Node h){
        h.color=Red;
        h.left.color= Black;
        h.right.color= Black;
    }

    public void put(Key key,Value value){
        root = put(root,key,value);
        root.color=Black;
    }

    private Node put(Node h, Key key, Value value) {
        if(h==null){
            return new Node(key,value,1,Red);
        }
        int cmp = key.compareTo(h.key);
        if(cmp<0)
            h.left=put(h.left,key,value);
        else if(cmp>0)
            h.right=put(h.right,key,value);
        else
            h.value=value;

        if(isRed(h.right)&&!isRed(h.left))  //左旋
            h=rotateLeft(h);
        if(isRed(h.left)&&isRed(h.left.left))  //右旋
            h=rotateRight(h);
        if(isRed(h.left)&&isRed(h.right))   //颜色转换
            flipColors(h);
        h.n=size(h.right)+size(h.left)+1 ;
        return h;
    }

    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);   //比自己大,往右边遍历
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值