class RBTree<T extends Comparable<T>> { private RBNode root; public RBTree(RBNode root) { this.root = root; } public RBNode getRoot() { return root; } private void leftRotate(RBNode x) { RBNode y = x.right; //x.right!=null x.right = y.left; if (y.left != null) { y.left.parent = x; } y.parent = x.parent; if (x.parent == null) { this.root = y; } else { if (x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } } y.left = x; x.parent = y; } private void rightRotate(RBNode y) { RBNode x = y.left; // x.left !=null y.left = x.right; if (x.right != null) { x.right.parent = y; } x.parent = y.parent; if (y.parent == null) { this.root = x; } else { if (y == y.parent.left) { y.parent.left = x; } else { y.parent.right = x; } } y.parent = x; x.right = y; } public void insert(T value) { RBNode<T> node = new RBNode<>(true, value, null, null, null); insertNode(node); } public void insertNode(RBNode node) { RBNode current = null; RBNode x = this.root; while (x != null) { current = x; int res = node.key.compareTo(x.key); if (res < 0) { x = x.left; } else { x = x.right; } } node.parent = x.parent; if (current == null) { int i = node.key.compareTo(current.key); if (i < 0) { current.left = node; } else { current.right = node; } } else { this.root = node; } insertFixUp(node); } private void insertFixUp(RBNode node) { RBNode parent, gparent; // 父节点为红色节点 while (((parent = node.parent) != null) && parent.color) { gparent = parent.parent; // 父节点 为祖父节点的左子节点 if (parent == gparent.left) { RBNode uncle = gparent.right; // 叔叔节点为 红色节点 if (Objects.nonNull(uncle) && uncle.color) { parent.color = false; uncle.color = false; gparent.color = true; node = gparent; continue; } // 叔叔是黑色 且当前节点是右孩子 if (parent.right == node) { leftRotate(parent); // 父节点处左旋 // parent node 交换位置 RBNode tmp = parent; parent = node; node = tmp; } parent.color = false; gparent.color = true; rightRotate(gparent); // 父节点 为 祖父节点的 右子节点 } else { RBNode uncle = gparent.left; if (Objects.nonNull(uncle) && uncle.color) { parent.color = false; uncle.color = false; gparent.color = true; node = gparent; continue; } if (parent.left == node) { rightRotate(parent); RBNode tmp = parent; parent = node; node = tmp; } parent.color = false; gparent.color = true; leftRotate(gparent); } } root.color = false; } }
class RBNode<T extends Comparable<T>> { boolean color; // red is true black is false default red T key; RBNode<T> left; RBNode<T> right; RBNode<T> parent; public RBNode(boolean color, T key, RBNode<T> left, RBNode<T> right, RBNode<T> parent) { this.color = color; this.key = key; this.left = left; this.right = right; this.parent = parent; } public T getKey() { return key; } @Override public String toString() { return "RBNode{" + "color=" + color + ", key=" + key + '}'; } }