Skip to content

Instantly share code, notes, and snippets.

@rosalogia
Created March 26, 2021 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosalogia/d8bd755884d44e0e9f409d0f099ca766 to your computer and use it in GitHub Desktop.
Save rosalogia/d8bd755884d44e0e9f409d0f099ca766 to your computer and use it in GitHub Desktop.
Left-Leaning Red Black Tree Insertion in Java
private static <Key extends Comparable<Key>, Value> boolean isRed(Node<Key, Value> root) {
return root != null && root.isRed;
}
private static <Key extends Comparable<Key>, Value> int size(Node<Key, Value> root) {
if (root == null) return 0;
return 1 + size(root.left) + size(root.right);
}
private static <Key extends Comparable<Key>, Value> Node<Key, Value> leftRotate(Node<Key, Value> root) {
var x = root.right;
root.right = x.left;
x.left = root;
x.isRed = root.isRed;
root.isRed = true;
return x;
}
private static <Key extends Comparable<Key>, Value> Node<Key, Value> rightRotate(Node<Key, Value> root) {
var x = root.left;
root.left = x.right;
x.right = root;
x.isRed = root.isRed;
root.isRed = true;
return x;
}
private static <Key extends Comparable<Key>, Value> void colorFlip(Node<Key, Value> root) {
root.isRed = true;
root.left.isRed = false;
root.right.isRed = false;
}
private static <Key extends Comparable<Key>, Value> Node<Key, Value> insert(Node<Key, Value> root, Key k, Value v) {
if (root == null) return new Node<>(k, v, true);
int comp = k.compareTo(root.key);
if (comp < 0) root.left = insert(root.left, k, v);
else if (comp > 0) root.right = insert(root.right, k, v);
else root.value = v;
if (!isRed(root.left) && isRed(root.right)) root = leftRotate(root);
if (isRed(root.left) && isRed(root.left.left)) root = rightRotate(root);
if (isRed(root.left) && isRed(root.right)) colorFlip(root);
root.size = size(root);
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment