Red Black Binary Search Tree: Part 1 put. Algorithms Series
Red-Black Tree is a Binary Search Tree with one extra bit of storage per node - color, which can be either RED or BLACK. We need it to keep BST “balanced”, that means basic dynamic set operations will be fast (guaranteed time O(lg n) ).
Red-black tree has next properties:
- Every node is RED or BLACK
- The root id always BlACK
- Every null leaf is black
- If a node is RED, then both children are BLACK
- For each node, all simple paths from the node to descendant leaves contain the same number of BLACK nodes.
To get started with test cases we need a skeleton first.
Methods get() and size() are the same as in Binary search tree.
PUT
Test cases for put should check that:
- value is present
- there is no more than 1 left RED links in the row
- there is no right RED link
- root should be always BLACK
Code for the implementation of put() method is very similar to BST implementation except conditions that balance tree. To achieve balance we need to implement rotateLeft(), rotateRight() and flipColors() methods first.
After those methods in place, we can complete the implementation.
Complete implementation with test cases can be found on GitHub.
Sources: