java实现红黑树

红黑树是一种平衡二叉搜索树,它的每个节点都有一个颜色属性,可以是红色或黑色。为了保证红黑树的平衡,它有以下五条性质:

  1. 每个节点要么是红色,要么是黑色。
  2. 根节点是黑色。
  3. 叶子节点(最后一层的节点)是黑色。
  4. 如果一个节点是红色,则它的两个儿子都是黑色。
  5. 对于每个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点。

下面是一个 Java 实现红黑树的例子:

```java public class RedBlackTree { private static final boolean RED = true; private static final boolean BLACK = false;

private classNode {
    int key;
    Node left;
    Node right;
    boolean color;

    Node(int key, boolean color) {
        this.key = key;
        this.color = color;
    }
}

private Node root;

private boolean isRed(Node node) {
    if (node == null) {
        return false;
    }
    return node.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 insert(int key) {
    root = insert(root, key);
    root.color = BLACK;
}

private Node insert(Node h, int key) {
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值