自平衡二进制搜索树是高度平衡的二进制搜索树,当对树执行插入和删除操作时,它们会自动使高度保持尽可能小。通常按Log n的顺序保持高度,以便所有操作平均花费O(Log n)时间。
例子 :
红黑树
AVL树:
语言实现:
在C++ STL中设置和映射。 Java的TreeSet和TreeMap。大多数库实现使用Red Black Tree。 Python标准库不支持Self Balancing BST。在Python,我们可以使用bisect模块来保留一组排序后的数据。我们还可以使用PyPi模块,例如rbtree(红黑树的实现)和pyavl(AVL树的实现)。
自平衡树如何保持身高?
树木完成的典型操作是旋转。以下是可以执行的两个基本操作,以在不违反BST属性的情况下重新平衡BST(键(左)<键(根)<键(右))。 1)左旋2)右旋
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.
我们已经讨论过AVL树,红黑树和Splay树。在本节中,我们将比较这些树的效率:
Metric | RB Tree | AVL Tree | Splay Tree |
---|---|---|---|
Insertion in worst case |
O(1) | 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 requires | Three pointers with color bit per node | Two 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 used | As universal data structure | When frequent lookups are required | When same element is retrieved again and again |
Real world Application | Multiset, Multimap, Map, Set, etc. | Database Transactions | Cache implementation, Garbage collection Algorithms |
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。