红黑树的实现

该博客详细介绍了红黑树的数据结构及其Java实现。内容包括红黑树节点的定义、颜色属性、旋转操作(左旋和右旋)以及颜色翻转等关键操作,展示了如何在红黑树中插入新节点并保持其平衡。此外,还提供了查找节点的实现方法。
摘要由CSDN通过智能技术生成
package DataStructure.tree;

public class RedBlackTree<Key extends Comparable<Key>,Value>{
    private Node root;
    private int N;
    private static final boolean Red=true;
    private static final boolean Black=false;
    private class Node{
        public Key key;
        public Value value;
        public Node left;
        public Node right;
        public boolean color;
        public Node(Key key,Value value,Node right,Node Left,boolean color){
            this.key=key;
            this.value=value;
            this.right=right;
            this.left=left;
            this.color=color;
        }
    }
    public int size(){
        return N;
    }
    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;
        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;
        return x;
    }
    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;
    }
    public Node put(Node h,Key key,Value value) {
        if(h==null){
            N++;
            return new Node(key,value,null,null,Black);
        }
        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);
        }
        return h;
    }
    public Value get(Key key){
        return get(root,key);
    }
    public 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;
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

outlier--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值