Junior — Middle
Can you explain the structure and main properties of red-black trees?
sobes.tech AI
Answer from AI
A red-black tree is a self-balancing binary search tree with an additional property of node colors (red or black), which ensures balancing and guarantees logarithmic time complexity for insertion, deletion, and search operations.
Main properties:
- Each node is either red or black.
- The root is always black.
- All leaves (NIL nodes) are considered black.
- If a node is red, then both its children are black (no two reds in a row).
- For each node, all paths from it to its descendant leaves contain the same number of black nodes (black height).
These properties ensure that the tree remains approximately balanced, preventing degeneration into a list.
An example of usage in Java is the TreeMap class, which is based on a red-black tree for storing keys in sorted order with efficient access.