Skip to content
Related Articles

Related Articles

Self-Balancing-Binary-Search-Trees (Comparisons)

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 02 Jun, 2022

Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keeps height as small as possible when insertion and deletion operations are performed on tree. The height is typically maintained in order of Log n so that all operations take O(Log n) time on average. 

Examples : 
Red Black Tree 
 

Red Black Tree

AVL Tree: 
 

Language Implementations : set and map in C++ STL. TreeSet and TreeMap in Java. Most of the library implementations use Red Black Tree. Python standard library does not support Self Balancing BST. In Python, we can use bisect module to keep a set of sorted data. We can also use PyPi modules like rbtree (implementation of red black tree) and pyavl (implementation of AVL tree). 

How do Self-Balancing-Tree maintain height? 
A typical operation done by trees is rotation. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 
1) Left Rotation 
2) Right Rotation 

 

T1, T2 and T3 are subtrees of the tree 
rooted with y (on the left side) or x (on 
the right side)           
     y                               x
    / \     Right Rotation          /  \
   x   T3   - - - - - - - >        T1   y 
  / \       < - - - - - - -            / \
 T1  T2     Left Rotation            T2  T3
Keys in both of the above trees follow the 
following order 
 keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.

We have already discussed AVL tree, Red Black Tree and Splay Tree. In this article, we will compare the efficiency of these trees: 
 

MetricRB TreeAVL TreeSplay Tree
Insertion in 
worst case
O(logn)O(logn)Amortized O(logn)
Maximum height 
of tree
2*log(n)1.44*log(n)O(n)
Search in 
worst case
O(logn), 
Moderate
O(logn), 
Faster
Amortized O(logn), 
Slower
Efficient Implementation requiresThree pointers with color bit per nodeTwo pointers with balance factor per 
node
Only two pointers with 
no extra information
Deletion in 
worst case
O(logn)O(logn)Amortized O(logn)
Mostly usedAs universal data structureWhen frequent lookups are requiredWhen same element is 
retrieved again and again
Real world ApplicationDatabase TransactionsMultiset, Multimap, Map, Set, etc.Cache implementation, Garbage collection Algorithms

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!