Java手写红黑树

手写红黑树

此代码学习与哔哩哔哩
点击视频链接

代码内有注释
注: 有插入,没有删除,视频没讲emmmm

package com.xiaojie;

import javax.xml.soap.Node;

public class RBTree<K extends Comparable<K>,V> {
    private static final boolean RED = true;
    private static final boolean BLACK=false;

    /**
     * 树根
     */
    private RBNode root;

    public RBNode getRoot() {
        return root;
    }
    /**
     * 获取当前节点的父节点
     *
     */
    private RBNode parentOf(RBNode node){
        if (node != null){
            return node.parent;
        }
        return null;
    }

    /**
     * 节点是否红色
     *
     */
    private boolean isRed(RBNode node){
        if (node!=null){
            return node.color == RED;
        }
        return false;
    }
    /**
     * 节点是否黑色
     *
     */
    private boolean isBlack(RBNode node){
        if (node!=null){
            return node.color == BLACK;
        }
        return true;
    }

    /**
     * 设置节点为红色
     *
     */
    private void setRed(RBNode node){
        if (node!=null){
            node.color = RED;
        }
    }
    /**
     * 设置节点为黑色
     *
     */
    private void setBlack(RBNode node){
        if (node!=null){
            node.color = BLACK;
        }
    }

    /**
     * 中序打印二叉树
     *
     */
    public void inOrderPrint(){
        inOrderPrint(this.root);
    }
    private void inOrderPrint(RBNode node){
        if (node != null){
            inOrderPrint(node.left);
            System.out.println("key: "+node.key+",  value: "+node.value);
            inOrderPrint(node.right);
        }
    }
    /*
    公开的插入方法
     */
    public void insert(K key,V value){
        RBNode node = new RBNode();
        node.setKey(key);
        node.setValue(value);
        node.setColor(RED);
        insert(node);
    }
    private void insert(RBNode node){
        //查找node父节点
        RBNode parent = null;
        RBNode x = this.root;
        while (x!=null){
            parent = x;
            //cmp>0说明node.key大于x的key,说明需要右边查找,
            //cmp==0说明替换
            //cmp<0,左边查
            int cmp = node.key.compareTo(x.key);
            if (cmp>0){
                x = x.right;
            }else if (cmp == 0){
                x.setValue(node.getValue());
                return;//退出
            }else {
                x = x.left;
            }
        }
        node.parent = parent;
        //判断左右
        if (parent!= null){
            int cmp = node.key.compareTo(parent.key);
            if (cmp > 0){
                parent.right = node;
            }else {
                parent.left = node;
            }
        }else {
            this.root = node;
        }

        //需要调用修复红黑树平衡方法
        insertFixup(node);
    }
    /*
    修复红黑平衡
    1.为空树,染色为黑
    2.插入节点父节点为黑色,不需要操作
    3.父节点为红色
        3.1.叔叔节点存在并且是红色,将叔叔和父亲染色为黑,爷爷变为红,并以爷爷为当前节点进行下一轮处理
        3.2.叔叔不存在或为黑色,父节点为爷爷的左边
            3.2.1.左左情况,将爸爸软成黑色,爷爷然红色,根据爷爷节点右旋
            3.2.2.左右情况,先根据父亲左旋得到ll双红,然后将父亲变儿子下一轮处理
        3.3.叔叔不存在或为黑色,父节点为爷爷的右边
            3.3.1.上面反转rr
            3.3.2.同上rl
     */
    private void insertFixup(RBNode node){

        this.root.setColor(BLACK);//1.为空树,染色为黑
        RBNode parent = parentOf(node);//拿到父亲
        RBNode gparent = parentOf(parent);//拿到爷爷
        //3.父节点为红色
        if (parent!=null && isRed(parent)){//父节点为红,一定存在爷爷节点
            RBNode uncle = null;
                if (parent == gparent.left){//如果爸爸是爷爷的左边,得出所以叔叔在右边
                    uncle = gparent.right;
                    //3.1.叔叔节点存在并且是红色,将叔叔和父亲染色为黑,爷爷变为红,并以爷爷为当前节点进行下一轮处理
                    if (uncle != null && isRed(uncle)){
                        setBlack(parent);
                        setBlack(uncle);
                        setRed(gparent);
                        insertFixup(gparent);//递归,直到递归上去的叔叔为黑或者为空
                        return;
                    }
                    // 3.2.叔叔不存在或为黑色,父节点为爷爷的左边
                    if (uncle == null || isBlack(uncle)){
                        //3.2.1.左左情况,将爸爸软成黑色,爷爷然红色,根据爷爷节点右旋
                        if (node==parent.left){
                            setBlack(parent);
                            setRed(gparent);
                            rightRotate(gparent);
                            return;//平衡了退出
                        }
                        // 3.2.2.左右情况,先根据父亲左旋得到ll双红,然后将父亲变儿子下一轮处理
                        if (node==parent.right){
                            leftRotate(parent);
                            insertFixup(parent);//结构已经打乱了,父亲成了儿子把父亲放入下一轮自动进入3.2.1
                            return;//平衡了退出
                        }
                    }
                }else {// 3.3.叔叔不存在或为黑色,父节点为爷爷的右边
                    uncle = gparent.left;//叔叔为左边
                    //3.1.叔叔节点存在并且是红色,将叔叔和父亲染色为黑,爷爷变为红,并以爷爷为当前节点进行下一轮处理
                    if (uncle != null && isRed(uncle)){
                        setBlack(parent);
                        setBlack(uncle);
                        setRed(gparent);
                        insertFixup(gparent);//递归,直到递归上去的叔叔为黑或者为空
                        return;
                    }
                    // 3.3.叔叔不存在或为黑色,父节点为爷爷的右边
                    if (uncle == null || isBlack(uncle)){
                        //3.3.1.右右情况,将爸爸软成黑色,爷爷然红色,根据爷爷节点左旋
                        if (node==parent.right){
                            setBlack(parent);
                            setRed(gparent);
                            leftRotate(gparent);
                            return;//平衡了退出
                        }
                        // 3.3.2.右左情况,先根据父亲左旋得到rr双红,然后将父亲变儿子下一轮处理
                        if (node==parent.left){
                            rightRotate(parent);
                            insertFixup(parent);//结构已经打乱了,父亲成了儿子把父亲放入下一轮自动进入3.3.1
                            return;//平衡了退出
                        }
                    }
                }
            }

        }
    /*
    左旋
     */
    private void leftRotate(RBNode x){
        //y的左变x的右边
        RBNode y = x.right;
        x.right = y.left;//变成右边
        if (y.left!=null){
            y.left.parent=x;//儿子
        }
        //y顶替x
        if (x.parent!=null){
            y.parent = x.parent;
            if (x==x.parent.left){//判断左右顶替
                x.parent.left = y;
            }else {
                x.parent.right=y;
            }
        }else {//说明x是跟节点,此时更新y为跟节点
            this.root = y;
            this.root.parent = null;
        }
        //将x父节点更新为y,将y的左边更新x
        x.parent = y;
        y.left = x;
    }
    /*
    右旋
     */
    private void  rightRotate(RBNode y){
        //将x的右边变成y左边
        RBNode x = y.left;
        y.left=x.right ;
        if (x.right!=null){
            x.right.parent = y;
        }

        //x顶替y
        if (y.parent!=null){
            x.parent = y.parent;
            if (y==y.parent.left){
                y.parent.left = x;
            }else {
                y.parent.right = x;
                this.root.parent = null;
            }
        }else {
            this.root=x;
        }
        //y父亲更新为x,x右边更新为y
        y.parent = x;
        x.right = y;
    }
    static class RBNode<K extends Comparable<K>,V>{
        private RBNode parent;//父节点
        private RBNode left;//左
        private RBNode right;//右边
        private boolean color;//颜色
        private K key;
        private V value;

        public RBNode(){}

        public RBNode(RBNode parent, RBNode left, RBNode right, boolean color, K key, V value) {
            this.parent = parent;
            this.left = left;
            this.right = right;
            this.color = color;
            this.key = key;
            this.value = value;
        }

        public RBNode getParent() {
            return parent;
        }

        public void setParent(RBNode parent) {
            this.parent = parent;
        }

        public RBNode getLeft() {
            return left;
        }

        public void setLeft(RBNode left) {
            this.left = left;
        }

        public RBNode getRight() {
            return right;
        }

        public void setRight(RBNode right) {
            this.right = right;
        }

        public boolean isColor() {
            return color;
        }

        public void setColor(boolean color) {
            this.color = color;
        }

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }
    }
}

显示树形类,老师给的,非手敲

package com.xiaojie;

public class TreeOperation {
      /*
    树的结构示例:
              1
            /   \
          2       3
         / \     / \
        4   5   6   7
    */

    // 用于获得树的层数
    public static int getTreeDepth(RBTree.RBNode root) {
        return root == null ? 0 : (1 + Math.max(getTreeDepth(root.getLeft()), getTreeDepth(root.getRight())));
    }


    private static void writeArray(RBTree.RBNode currNode, int rowIndex, int columnIndex, String[][] res, int treeDepth) {
        // 保证输入的树不为空
        if (currNode == null) return;
        // 先将当前节点保存到二维数组中
        res[rowIndex][columnIndex] = String.valueOf(currNode.getKey() + "-" + (currNode.isColor() ? "R" : "B") + "");

        // 计算当前位于树的第几层
        int currLevel = ((rowIndex + 1) / 2);
        // 若到了最后一层,则返回
        if (currLevel == treeDepth) return;
        // 计算当前行到下一行,每个元素之间的间隔(下一行的列索引与当前元素的列索引之间的间隔)
        int gap = treeDepth - currLevel - 1;

        // 对左儿子进行判断,若有左儿子,则记录相应的"/"与左儿子的值
        if (currNode.getLeft() != null) {
            res[rowIndex + 1][columnIndex - gap] = "/";
            writeArray(currNode.getLeft(), rowIndex + 2, columnIndex - gap * 2, res, treeDepth);
        }

        // 对右儿子进行判断,若有右儿子,则记录相应的"\"与右儿子的值
        if (currNode.getRight() != null) {
            res[rowIndex + 1][columnIndex + gap] = "\\";
            writeArray(currNode.getRight(), rowIndex + 2, columnIndex + gap * 2, res, treeDepth);
        }
    }


    public static void show(RBTree.RBNode root) {
        if (root == null) System.out.println("EMPTY!");
        // 得到树的深度
        int treeDepth = getTreeDepth(root);

        // 最后一行的宽度为2的(n - 1)次方乘3,再加1
        // 作为整个二维数组的宽度
        int arrayHeight = treeDepth * 2 - 1;
        int arrayWidth = (2 << (treeDepth - 2)) * 3 + 1;
        // 用一个字符串数组来存储每个位置应显示的元素
        String[][] res = new String[arrayHeight][arrayWidth];
        // 对数组进行初始化,默认为一个空格
        for (int i = 0; i < arrayHeight; i ++) {
            for (int j = 0; j < arrayWidth; j ++) {
                res[i][j] = " ";
            }
        }

        // 从根节点开始,递归处理整个树
        // res[0][(arrayWidth + 1)/ 2] = (char)(root.val + '0');
        writeArray(root, 0, arrayWidth/ 2, res, treeDepth);

        // 此时,已经将所有需要显示的元素储存到了二维数组中,将其拼接并打印即可
        for (String[] line: res) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < line.length; i ++) {
                sb.append(line[i]);
                if (line[i].length() > 1 && i <= line.length - 1) {
                    i += line[i].length() > 4 ? 2: line[i].length() - 1;
                }
            }
            System.out.println(sb.toString());
        }
    }
}


测试是否写好
只用了key,value直接空

package com.xiaojie;

import java.util.Scanner;

public class RBTreeTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        RBTree<String,String> rbt = new RBTree<>();
        while (true){
            System.out.println("输入key: ");
            String key = scanner.next();
            System.out.println();
            rbt.insert(key,null);
            TreeOperation.show(rbt.getRoot());
        }
    }
}

结果图
B-黑色
R-红色
在这里插入图片描述
关于10以上比较出问题的事情
比对节点大小时 直接使用的是 node.key.compareTo(parent.key);
这个其实是按照字符串比对的! 所以,大家尽量使用 a,b,c,d,e,f,g,h,i…这种风格去测试…
或者自己改改这块的逻辑,

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值