Java Implementations

Node Implementation

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

class TreeNode{
    private Key key;
    private Value val;
    private TreeNode left;
    private TreeNode right;
    private boolean color;
    
    // ....... constructor ........
}

private boolean isRed(Node x){
    if(x == null) return false;
    return x.color == RED;
}

Search Operation

Observation. Search is the same as for elementary BST ( ignore color ).

Elementary operations

Left Rotation

Right Rotation

Invariants: Maintains symmetric order and perfect black balance.

Color Flip

Insertion

Basic Strategy: Maintain 1-1 correspondence with 2-3 trees by applying elementary red-black BST operations.

Case 1: Into Exactly 2-node

  • Do standard BST insert; color new link red

  • If new red link is a right link, rotate left.

Explanation for inserting a node in 2-node

Example: Insert ' C '

Example for inserting a node in 2-node

Case 2: Insert into 3-node

  • Do standard BST insert; color new link red.

  • Rotate to balance the 4-node ( if needed ).

  • Flip colors to pass red link up one level.

  • Rotate to make lean left (if needed).

Explanation for inserting a node in 3-node

Example: Inserting ' H '

Example for inserting a node in 3-node Red Black Tree
  • Do standard BST insert; color new link red.

  • Rotate to balance the 4-node ( if needed ).

  • Flip colors to pass red link up one level.

  • Rotate to make lean left (if needed).

  • Repeat case 1, case 2 ( if needed ).

Example:

Java Implementation

Delete

Delete operations are bit complicated.

Last updated

Was this helpful?