Java数据结构与算法笔记——红黑树详解

二叉搜索树缺点

二叉搜索树对于某个节点而言,其左子树的节点关键值都小于该节点关键值,右子树的所有节点关键值都大于该节点关键值。二叉搜索树作为一种数据结构,其查找、插入和删除操作的时间复杂度都为O(logn),底数为2。

但是我们说这个时间复杂度是在平衡的二叉搜索树上体现的,也就是如果插入的数据是随机的,则效率很高,但是如果插入的数据是有序的,比如从小到大的顺序【10,20,30,40,50】插入到二叉搜索树中:
在这里插入图片描述
从大到小就是全部在左边,这和链表没有任何区别了,这种情况下查找的时间复杂度为O(N),而不是O(logN)。当然这是在最不平衡的条件下,实际情况下,二叉搜索树的效率应该在O(N)和O(logN)之间,这取决于树的不平衡程度

红黑树

红黑树简介

为了能够以较快的时间O(logN)来搜索一棵树,我们需要保证树总是平衡的(或者大部分是平衡的),也就是说每个节点的左子树节点个数和右子树节点个数尽量相等。

红-黑树的就是这样的一棵平衡的二叉搜索树,对一个要插入的数据项(删除也是),插入过程要检查会不会破坏树的特征,如果破坏了,程序就会进行纠正,根据需要改变树的结构,从而保持树的平衡。

红黑树规则

红黑树有必须要遵守的规则,称为红-黑规则:

  1. 每个节点不是红色就是黑色的;
  2. 根节点总是黑色的
  3. 红色节点的子节点必须是黑色的(反之不一定)。也就是从每个叶子到根的路径上不能有两个连续的红色节点;
  4. 从根节点到叶节点或空子节点的每条路径,必须包含相同数目的黑色节点(即相同的黑色高度)。

红黑树自我修正

当进行插入或者删除节点操作时,如果违反了规则,就要进行红黑树的自我修正。红黑树有三种自我修正方式,分别是:改变节点颜色、右旋、左旋。

注意:我们改变颜色也是为了帮助我们判断何时执行什么旋转,而旋转是为了保证树的平衡。只改变节点颜色是不能起到任何作用的,旋转才是关键的操作

改变节点颜色

在这里插入图片描述
新插入的节点为15,一般新插入颜色都为红色,那么我们发现直接插入会违反规则3。这时候我们将其父节点颜色改为黑色,父节点的兄弟节点颜色也改为黑色。

右旋

在这里插入图片描述
首先要说明的是节点本身是不会旋转的,旋转改变的是节点之间的关系,选择一个节点作为旋转的顶端,如果做一次右旋,这个顶端节点会向下和向右移动到它右子节点的位置,它的左子节点会上移到它原来的位置。右旋的顶端节点必须要有左子节点

  • Y.leftChild = β
  • X.rightChild = Y
  • parent.child = X

左旋

在这里插入图片描述
左旋的节点必须要有右子节点。

  • X.rightChild = β
  • Y.leftChild = X
  • parent.child = Y

插入节点

新插入的节点颜色总是红色的,这是因为插入一个红色节点比插入一个黑色节点违背红-黑规则的可能性更小。

插入黑色节点总会改变黑色高度(违背规则4),但是插入红色节点只有一半的概论违背规则3(父节点如果是黑色就没事儿,父节点是红色会违背3)。另外,违背规则3比违背规则4要更容易修正。

红黑树插入节点纠正算法

在新增节点或者删除节点之后,可能会破坏二叉树的平衡,那么我们需要确认何时变色、左旋以及右旋。

如果是第一次插入,由于原树为空,所以只会违反红-黑树的规则2,所以只要把根节点涂黑即可;
如果插入节点的父节点是黑色的,那不会违背红-黑树的规则,什么也不需要做;
但是遇到如下三种情况,我们就要开始变色和旋转了:

  1. 插入节点的父节点和其叔叔节点(祖父节点的另一个子节点)均为红色。
  2. 插入节点的父节点是红色的,叔叔节点是黑色的,且插入节点是其父节点的右子节点。
  3. 插入节点的父节点是红色的,叔叔节点是黑色的,且插入节点是其父节点的左子节点。

在下面的分析中,我们使用N(now)表示当前节点,P(parent)表示N的父节点,U(uncle)表示N的叔叔节 点,G(grandfather)表示N的祖父节点。

对于情况1

插入节点的父节点和其叔叔节点(祖父节点的另一个子节点)均为红色。

此时,肯定存在祖父节点,但是不知道父节点是其左子节点还是右子节点,但是由于对称性,我们只要讨论出一边的情况,另一种情况自然也与之对称。这里考虑父节点是其祖父节点的左子节点的情况,如下左图所示:
在这里插入图片描述
对于这种情况,我们要做的操作有:
将当前节点(4) 的父节点(5) 和叔叔节点(8) 涂黑,将祖父节点(7)涂红,变成了下图所示的情况。再将当前节点指向其祖父节点(7),再次从新的当前节点开始算法(具体看下面的步骤)。这样就变成情况2了
在这里插入图片描述

对于情况2

将当前节点(7)的父节点(2)作为新的节点,以新的当前节点为支点做左旋操作。完成之后就变成了情况3
在这里插入图片描述

对于情况3

将当前节点的父节点(7)涂黑。将祖父节点(11)涂红,在祖父节点为支点做右旋操作。整个红-黑树就恢复了平衡
在这里插入图片描述
我们可以看出,如果是从情况1开始发生的,必然会走完情况2和3,也就是说这是一整个流程。实际中可能不一定会从情况1发生,如果从情况2开始发生,那再走个情况3即可完成调整,如果直接只要调整情况3,那么前两种情况均不需要调整了。

删除节点

从红黑树内删除一个节点,需要执行的操作依次是:

  1. 将红黑树当做一颗二叉查找树,将节点从二叉查找树中删除。
  2. 通过自我修正算法修正红黑树。

红黑树性能分析

红黑树的查找、插入和删除时间复杂度都为O(logN),额外的开销是每个节点的存储空间都稍微增加了一点,因为一个存储红黑树节点的颜色变量。插入和删除的时间要增加一个常数因子,因为要进行旋转,平均一次插入大约需要一次旋转,因此插入的时间复杂度还是 O(logN),(时间复杂度的计算要省略常数),但实际上红黑树的插入和删除比普通的二叉树是要慢的

红黑树适用于查找的次数比插入和删除的次数大很多的情况,红黑树的优点是对于有序数据的操作不会慢到O(N)的时间复杂度

红黑树实现代码

代码转自“skywang12345”的博客,网址:https://www.cnblogs.com/skywang12345/p/3624343.html

红黑树实现的类

package rbTree;

public class RBTree<T extends Comparable<T>> {

    private RBTNode<T> mRoot;    // 根结点

    private static final boolean RED   = false;
    private static final boolean BLACK = true;

    /**
     * 封装节点的类
     * @param <T>
     */
    public static class RBTNode<T extends Comparable<T>> {
        boolean color;        // 颜色
        T key;                // 关键字(键值)
        RBTNode<T> left;    // 左孩子
        RBTNode<T> right;    // 右孩子
        RBTNode<T> parent;    // 父结点

        public RBTNode(T key, boolean color, RBTNode<T> parent, RBTNode<T> left, RBTNode<T> right) {
            this.key = key;
            this.color = color;
            this.parent = parent;
            this.left = left;
            this.right = right;
        }

        public T getKey() {
            return key;
        }

        public String toString() {
            return ""+key+(this.color==RED?"(R)":"B");
        }
    }

    /**
     * 构造方法
     */
    public RBTree() {
        mRoot=null;
    }

    /**
     * 返回节点的父节点,如果节点为空,返回null
     */
    private RBTNode<T> parentOf(RBTNode<T> node) {
        return node!=null ? node.parent : null;
    }

    /**
     * 返回节点颜色
     */
    private boolean colorOf(RBTNode<T> node) {
        return node!=null ? node.color : BLACK;
    }

    /**
     * 判断节点颜色
     */
    private boolean isRed(RBTNode<T> node) {
        return (node != null) && (node.color == RED);
    }
    private boolean isBlack(RBTNode<T> node) {
        return (node != null) && (node.color == BLACK);
    }

    /**
     * 设置节点颜色
     */
    private void setBlack(RBTNode<T> node) {
        if (node!=null)
            node.color = BLACK;
    }
    private void setRed(RBTNode<T> node) {
        if (node!=null)
            node.color = RED;
    }

    /**
     * 设置节点的父节点
     * @param node 节点
     * @param parent 父节点
     */
    private void setParent(RBTNode<T> node, RBTNode<T> parent) {
        if (node!=null)
            node.parent = parent;
    }

    /**
     * 设置节点颜色
     */
    private void setColor(RBTNode<T> node, boolean color) {
        if (node!=null)
            node.color = color;
    }

    /**
     * 前序遍历"红黑树"
     */
    private void preOrder(RBTNode<T> tree) {
        if(tree != null) {
            System.out.print(tree.key+" ");
            preOrder(tree.left);
            preOrder(tree.right);
        }
    }

    public void preOrder() {
        preOrder(mRoot);
    }

    /**
     * 中序遍历"红黑树"
     */
    private void inOrder(RBTNode<T> tree) {
        if(tree != null) {
            inOrder(tree.left);
            System.out.print(tree.key+" ");
            inOrder(tree.right);
        }
    }

    public void inOrder() {
        inOrder(mRoot);
    }


    /**
     * 后序遍历"红黑树"
     */
    private void postOrder(RBTNode<T> tree) {
        if(tree != null)
        {
            postOrder(tree.left);
            postOrder(tree.right);
            System.out.print(tree.key+" ");
        }
    }

    public void postOrder() {
        postOrder(mRoot);
    }


    /**
     * (递归实现)查找"红黑树x"中键值为key的节点
     */
    //从x节点开始查找
    private RBTNode<T> search(RBTNode<T> x, T key) {
        if (x==null) return x;

        int cmp = key.compareTo(x.key);
        if (cmp < 0){
            return search(x.left, key);
        }
        else if (cmp > 0){
            return search(x.right, key);
        }
        else{
            return x;
        }

    }

    //从根节点开始查找
    public RBTNode<T> search(T key) {
        return search(mRoot, key);
    }


    /**
     * (非递归实现)查找"红黑树x"中键值为key的节点
     */
    //从x节点开始查找
    private RBTNode<T> iterativeSearch(RBTNode<T> x, T key) {
        while (x!=null) {
            int cmp = key.compareTo(x.key);

            if (cmp < 0){
                x = x.left;
            }
            else if (cmp > 0){
                x = x.right;
            }
            else{
                //找到了
                return x;
            }
        }
        //x为空,或者没找到
        return x;
    }

    //从跟节点开始查找
    public RBTNode<T> iterativeSearch(T key) {
        return iterativeSearch(mRoot, key);
    }

    /**
     * 查找最小结点:返回tree为根结点的红黑树的最小结点。
     */
    private RBTNode<T> minimum(RBTNode<T> tree) {
        if (tree == null)
            return null;

        while(tree.left != null)
            tree = tree.left;
        return tree;
    }

    public T minimum() {
        RBTNode<T> p = minimum(mRoot);
        if (p != null) return p.key;
        return null;
    }

    /**
     * 查找最大结点:返回tree为根结点的红黑树的最大结点。
     */
    private RBTNode<T> maximum(RBTNode<T> tree) {
        if (tree == null){
            return null;
        }

        while(tree.right != null){
            tree = tree.right;
        }
        return tree;
    }
    //返回最大节点的值
    public T maximum() {
        RBTNode<T> p = maximum(mRoot);
        if (p != null){
            return p.key;
        }
        return null;
    }

    /**
     * 找结点(x)的后继结点。即,查找"红黑树中数据值大于该结点"的"最小结点"。
     */
    public RBTNode<T> successor(RBTNode<T> x) {
        // 如果x存在右孩子,则"x的后继结点"为 "以其右孩子为根的子树的最小结点"。
        if (x.right != null){
            return minimum(x.right);
        }

        // 如果x没有右孩子。则x有以下两种可能:
        // (01) x是"一个左孩子",则"x的后继结点"为 "它的父结点"。
        // (02) x是"一个右孩子",则查找"x的最低的父结点,并且该父结点要具有左孩子,x在最低父节点的左子树上",找到的这个"最低的父结点"就是"x的后继结点"。
        RBTNode<T> y = x.parent;
        while ((y!=null) && (x==y.right)) {
            x = y;
            y = y.parent;
        }

        return y;
    }

    /**
     * 找结点(x)的前驱结点。即,查找"红黑树中数据值小于该结点"的"最大结点"。
     */
    public RBTNode<T> predecessor(RBTNode<T> x) {
        // 如果x存在左孩子,则"x的前驱结点"为 "以其左孩子为根的子树的最大结点"。
        if (x.left != null){
            return maximum(x.left);
        }

        // 如果x没有左孩子。则x有以下两种可能:
        // (01) x是"一个右孩子",则"x的前驱结点"为 "它的父结点"。
        // (01) x是"一个左孩子",则查找"x的最低的父结点,并且该父结点要具有右孩子,x在它的右子树上",找到的这个"最低的父结点"就是"x的前驱结点"。
        RBTNode<T> y = x.parent;
        while ((y!=null) && (x==y.left)) {
            x = y;
            y = y.parent;
        }
        return y;
    }

    /**
     * 对红黑树的节点(x)进行左旋转
     *
     * 左旋示意图(对节点x进行左旋):
     *      px                              px
     *     /                               /
     *    x                               y
     *   /  \      --(左旋)-->           / \                #
     *  lx   y                          x  ry
     *     /   \                       / \
     *    ly   ry                     lx  ly
     *
     *
     */
    private void leftRotate(RBTNode<T> x) {
        // 设置x的右孩子为y
        RBTNode<T> y = x.right;

        // 将 “y的左孩子” 设为 “x的右孩子”;
        // 如果y的左孩子非空,将 “x” 设为 “y的左孩子的父亲”
        x.right = y.left;
        if (y.left != null){
            y.left.parent = x;
        }

        // 将 “x的父亲” 设为 “y的父亲”
        y.parent = x.parent;

        if (x.parent == null) {
            this.mRoot = y;            // 如果 “x的父亲” 是空节点,则将y设为根节点
        } else {
            if (x.parent.left == x){
                x.parent.left = y;    // 如果 x是它父节点的左孩子,则将y设为“x的父节点的左孩子”
            }
            else{
                x.parent.right = y;    // 如果 x是它父节点的右孩子,则将y设为“x的父节点的右孩子”
            }

        }

        // 将 “x” 设为 “y的左孩子”
        y.left = x;
        // 将 “x的父节点” 设为 “y”
        x.parent = y;
    }

    /**
     * 对红黑树的节点(y)进行右旋转
     *
     * 右旋示意图(对节点y进行左旋):
     *            py                               py
     *           /                                /
     *          y                                x
     *         /  \      --(右旋)-.            /  \                     #
     *        x   ry                           lx   y
     *       / \                                   / \                   #
     *      lx  rx                                rx  ry
     *
     */
    private void rightRotate(RBTNode<T> y) {
        // 设置x是当前节点的左孩子。
        RBTNode<T> x = y.left;

        // 将 “x的右孩子” 设为 “y的左孩子”;
        // 如果"x的右孩子"不为空的话,将 “y” 设为 “x的右孩子的父亲”
        y.left = x.right;
        if (x.right != null){
            x.right.parent = y;
        }

        // 将 “y的父亲” 设为 “x的父亲”
        x.parent = y.parent;

        if (y.parent == null) {
            this.mRoot = x;            // 如果 “y的父亲” 是空节点,则将x设为根节点
        } else {
            if (y == y.parent.right){
                y.parent.right = x;    // 如果 y是它父节点的右孩子,则将x设为“y的父节点的右孩子”
            }
            else{
                y.parent.left = x;    // (y是它父节点的左孩子) 将x设为“y的父节点的左孩子”
            }

        }

        // 将 “y” 设为 “x的右孩子”
        x.right = y;

        // 将 “y的父节点” 设为 “x”
        y.parent = x;
    }

    /**
     * 红黑树插入修正函数
     *
     * 在向红黑树中插入节点之后(失去平衡),再调用该函数;
     * 目的是将它重新塑造成一颗红黑树。
     *
     * 参数说明:
     *     node 插入的结点
     */
    private void insertFixUp(RBTNode<T> node) {
        RBTNode<T> parent, gparent;

        // 若“父节点存在,并且父节点的颜色是红色”
        while (((parent = parentOf(node))!=null) && isRed(parent)) {
            gparent = parentOf(parent);

            //若“父节点”是“祖父节点的左孩子”
            if (parent == gparent.left) {
                // Case 1条件:叔叔节点是红色
                RBTNode<T> uncle = gparent.right;
                if ((uncle!=null) && isRed(uncle)) {
                    setBlack(uncle);
                    setBlack(parent);
                    setRed(gparent);
                    node = gparent;
                    continue;
                }

                // Case 2条件:叔叔是黑色,且当前节点是其父节点的右孩子
                if (parent.right == node) {
                    RBTNode<T> tmp;
                    leftRotate(parent);
                    tmp = parent;
                    parent = node;
                    node = tmp;
                }

                // Case 3条件:叔叔是黑色,且当前节点是左孩子。
                setBlack(parent);
                setRed(gparent);
                rightRotate(gparent);
            } else {    //若“z的父节点”是“z的祖父节点的右孩子”
                // Case 1条件:叔叔节点是红色
                RBTNode<T> uncle = gparent.left;
                if ((uncle!=null) && isRed(uncle)) {
                    setBlack(uncle);
                    setBlack(parent);
                    setRed(gparent);
                    node = gparent;
                    continue;
                }

                // Case 2条件:叔叔是黑色,且当前节点是左孩子
                if (parent.left == node) {
                    RBTNode<T> tmp;
                    rightRotate(parent);
                    tmp = parent;
                    parent = node;
                    node = tmp;
                }

                // Case 3条件:叔叔是黑色,且当前节点是右孩子。
                setBlack(parent);
                setRed(gparent);
                leftRotate(gparent);
            }
        }

        // 将根节点设为黑色
        setBlack(this.mRoot);
    }

    /**
     * 将结点插入到红黑树中
     *
     * 参数说明:
     *     node 插入的结点        // 对应《算法导论》中的node
     */
    private void insert(RBTNode<T> node) {
        int cmp;
        RBTNode<T> y = null;
        RBTNode<T> x = this.mRoot;

        // 1. 将红黑树当作一颗二叉查找树,将节点添加到二叉查找树中。
        while (x != null) {
            y = x;
            cmp = node.key.compareTo(x.key);
            if (cmp < 0){
                x = x.left;
            }
            else{
                x = x.right;
            }
        }

        //结束while循环后,y停在一个叶子节点上
        node.parent = y;
        if (y!=null) {
            cmp = node.key.compareTo(y.key);
            if (cmp < 0){
                y.left = node;
            }
            else{
                y.right = node;
            }
        } else {
            //mRoot==null才会进入到这儿
            this.mRoot = node;
        }

        // 2. 设置节点的颜色为红色
        node.color = RED;

        // 3. 将它重新修正为一颗二叉查找树
        insertFixUp(node);
    }

    /**
     * 新建结点(key),并将其插入到红黑树中
     *
     * 参数说明:
     *     key 插入结点的键值
     */
    public void insert(T key) {
        RBTNode<T> node= new RBTNode<T>(key, BLACK, null, null, null);

        // 如果新建结点失败,则返回。
        if (node != null){
            insert(node);
        }
    }


    /**
     * 红黑树删除修正函数
     *
     * 在从红黑树中删除插入节点之后(红黑树失去平衡),再调用该函数;
     * 目的是将它重新塑造成一颗红黑树。
     *
     * 参数说明:
     *     node 待修正的节点
     */
    private void removeFixUp(RBTNode<T> node, RBTNode<T> parent) {
        RBTNode<T> other;//兄弟节点

        while ((node==null || isBlack(node)) && (node != this.mRoot)) {
            if (parent.left == node) {
                //当前节点是父节点的左子节点
                other = parent.right;
                if (isRed(other)) {
                    // Case 1: x的兄弟w是红色的
                    setBlack(other);
                    setRed(parent);
                    leftRotate(parent);
                    other = parent.right;
                }

                if ((other.left==null || isBlack(other.left)) &&
                        (other.right==null || isBlack(other.right))) {
                    // Case 2: x的兄弟w是黑色,且w的俩个孩子也都是黑色的
                    setRed(other);
                    node = parent;
                    parent = parentOf(node);
                } else {

                    if (other.right==null || isBlack(other.right)) {
                        // Case 3: x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。
                        setBlack(other.left);
                        setRed(other);
                        rightRotate(other);
                        other = parent.right;
                    }
                    // Case 4: x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。
                    setColor(other, colorOf(parent));
                    setBlack(parent);
                    setBlack(other.right);
                    leftRotate(parent);
                    node = this.mRoot;
                    break;
                }
            } else {
                //当前节点是父节点的右子节点
                other = parent.left;
                if (isRed(other)) {
                    // Case 1: x的兄弟w是红色的
                    setBlack(other);
                    setRed(parent);
                    rightRotate(parent);
                    other = parent.left;
                }

                if ((other.left==null || isBlack(other.left)) &&
                        (other.right==null || isBlack(other.right))) {
                    // Case 2: x的兄弟w是黑色,且w的俩个孩子也都是黑色的
                    setRed(other);
                    node = parent;
                    parent = parentOf(node);
                } else {

                    if (other.left==null || isBlack(other.left)) {
                        // Case 3: x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。
                        setBlack(other.right);
                        setRed(other);
                        leftRotate(other);
                        other = parent.left;
                    }

                    // Case 4: x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。
                    setColor(other, colorOf(parent));
                    setBlack(parent);
                    setBlack(other.left);
                    rightRotate(parent);
                    node = this.mRoot;
                    break;
                }
            }
        }

        if (node!=null)
            setBlack(node);
    }

    /**
     * 删除结点(node)
     *
     * 参数说明:
     *     node 删除的结点
     */
    private void remove(RBTNode<T> node) {
        RBTNode<T> child, parent;
        boolean color;

        // 被删除节点的"左右孩子都不为空"的情况。
        if ( (node.left!=null) && (node.right!=null) ) {
            // 被删节点的后继节点。(称为"取代节点")
            // 用它来取代"被删节点"的位置,然后再将"被删节点"去掉。
            RBTNode<T> replace = node;

            // 获取后继节点
            replace = replace.right;
            while (replace.left != null){
                replace = replace.left;
            }


            if (parentOf(node)!=null) {
                // "node节点"不是根节点(只有根节点不存在父节点)
                if (parentOf(node).left == node){
                    parentOf(node).left = replace;
                }
                else{
                    parentOf(node).right = replace;
                }
            } else {
                // "node节点"是根节点,更新根节点。
                this.mRoot = replace;
            }

            // child是"取代节点"的右孩子,也是需要"调整的节点"。
            // "取代节点"肯定不存在左孩子!因为它是一个后继节点。
            child = replace.right;
            parent = parentOf(replace);
            // 保存"取代节点"的颜色
            color = colorOf(replace);

            // "被删除节点"是"它的后继节点的父节点"
            if (parent == node) {
                parent = replace;
            } else {
                // child不为空
                if (child!=null){
                    setParent(child, parent);
                }
                parent.left = child;

                replace.right = node.right;
                setParent(node.right, replace);
            }

            replace.parent = node.parent;
            replace.color = node.color;
            replace.left = node.left;
            node.left.parent = replace;

            if (color == BLACK){
                removeFixUp(child, parent);
            }

            node = null;
            return ;
        }

        if (node.left !=null) {
            child = node.left;
        } else {
            child = node.right;
        }

        parent = node.parent;
        // 保存"取代节点"的颜色
        color = node.color;

        if (child!=null){
            child.parent = parent;
        }

        // "node节点"不是根节点
        if (parent!=null) {
            if (parent.left == node){
                parent.left = child;
            }
            else{
                parent.right = child;
            }
        } else {
            this.mRoot = child;
        }

        if (color == BLACK){
            removeFixUp(child, parent);
        }
        node = null;
    }

    /**
     * 根据节点的key删除结点
     *
     */
    public void remove(T key) {
        RBTNode<T> node;

        if ((node = search(mRoot, key)) != null){
            remove(node);
        }
    }

    /**
     * 销毁红黑树
     */
    private void destroy(RBTNode<T> tree) {
        if (tree==null){
            return ;
        }

        if (tree.left != null){
            destroy(tree.left);
        }

        if (tree.right != null){
            destroy(tree.right);
        }

        tree=null;
    }

    public void clear() {
        destroy(mRoot);
        mRoot = null;
    }

    /**
     * 打印"红黑树"
     *
     * key        -- 节点的键值
     * direction  --  0,表示该节点是根节点;
     *               -1,表示该节点是它的父结点的左孩子;
     *                1,表示该节点是它的父结点的右孩子。
     */
    private void print(RBTNode<T> tree, T key, int direction) {

        if(tree != null) {

            if(direction==0)    // tree是根节点
                System.out.printf("%2d(B) is root\n", tree.key);
            else                // tree是分支节点
                System.out.printf("%2d(%s) is %2d's %6s child\n", tree.key, isRed(tree)?"R":"B", key, direction==1?"right" : "left");

            print(tree.left, tree.key, -1);
            print(tree.right,tree.key,  1);
        }
    }

    public void print() {
        if (mRoot != null)
            print(mRoot, mRoot.key, 0);
    }
}

红黑树测试的类

package rbTree;

/**
 * Java 语言: 二叉查找树
 *
 * @author skywang
 * @date 2013/11/07
 */
public class RBTreeTest {

    private static final int[] a = {10, 40, 30, 60, 90, 70, 20, 50, 80};
    private static final boolean mDebugInsert = false;    // "插入"动作的检测开关(false,关闭;true,打开)
    private static final boolean mDebugDelete = false;    // "删除"动作的检测开关(false,关闭;true,打开)

    public static void main(String[] args) {
        int i, ilen = a.length;
        RBTree<Integer> tree=new RBTree<Integer>();

        //输出原始数据
        System.out.print("== 原始数据: ");
        for(i=0; i<ilen; i++)
            System.out.printf("%d ", a[i]);
        System.out.println();

        for(i=0; i<ilen; i++) {
            tree.insert(a[i]);
            // 设置mDebugInsert=true,测试"添加函数"
            if (mDebugInsert) {
                System.out.printf("== 添加节点: %d\n", a[i]);
                System.out.print("== 树的详细信息: \n");
                tree.print();
                System.out.println();
            }
        }

        System.out.print("== 前序遍历: ");
        tree.preOrder();

        System.out.print("\n== 中序遍历: ");
        tree.inOrder();

        System.out.print("\n== 后序遍历: ");
        tree.postOrder();
        System.out.print("\n");

        System.out.printf("== 最小值: %s\n", tree.minimum());
        System.out.printf("== 最大值: %s\n", tree.maximum());
        System.out.print("== 树的详细信息: \n");
        tree.print();
        System.out.print("\n");

        // 设置mDebugDelete=true,测试"删除函数"
        if (mDebugDelete) {
            for(i=0; i<ilen; i++)
            {
                tree.remove(a[i]);

                System.out.printf("== 删除节点: %d\n", a[i]);
                System.out.print("== 树的详细信息: \n");
                tree.print();
                System.out.print("\n");
            }
        }

        // 销毁二叉树
        tree.clear();
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值