Red-Black Tree - Problem

Implement a Red-Black Tree data structure with the following operations:

  • insert(value) - Insert a value while maintaining RB-Tree properties
  • delete(value) - Delete a value while maintaining RB-Tree properties
  • search(value) - Search for a value in the tree

A Red-Black Tree must maintain these five properties:

  1. Every node is either red or black
  2. The root is always black
  3. All leaves (NIL nodes) are black
  4. Red nodes cannot have red children (no two red nodes are adjacent)
  5. Every path from root to leaf contains the same number of black nodes

Return the final tree structure as an array representation after all operations.

Input & Output

Example 1 — Basic Insert Operations
$ Input: operations = [["insert",5],["insert",3],["insert",7],["search",3]]
Output: [5,3,7]
💡 Note: Insert 5 as root (black), insert 3 and 7 as red children. Tree maintains RB properties with root black and balanced structure.
Example 2 — Multiple Operations
$ Input: operations = [["insert",10],["insert",5],["insert",15],["insert",3],["search",5]]
Output: [10,5,15,3]
💡 Note: Build a balanced RB-tree with multiple inserts. Colors are assigned to maintain all five RB-tree properties.
Example 3 — Single Node
$ Input: operations = [["insert",42],["search",42]]
Output: [42]
💡 Note: Single node tree with root colored black, satisfying all RB-tree properties.

Constraints

  • 1 ≤ operations.length ≤ 103
  • operations[i] is one of ["insert", val], ["delete", val], or ["search", val]
  • 1 ≤ val ≤ 104
  • Tree maintains all five Red-Black properties

Visualization

Tap to expand
INPUTALGORITHMRESULTOperations:insert(5), insert(3)insert(7), search(3)537Colors: Black rootRed children1Insert as BST2Color nodes3Check violations4Apply fixupsMaintain 5 Properties:Root black, no red-redEqual black height537Output: [5,3,7]Balanced structureO(log n) operationsKey Insight:Red-Black trees use rotations and recoloring to maintain perfect balance,guaranteeing O(log n) height and efficient operations through structural rules.TutorialsPoint - Red-Black Tree | Self-Balancing Implementation
Asked in
Google 45 Microsoft 38 Amazon 32 Facebook 28
23.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen