平衡查找树

71 阅读1分钟

avl

左右子树的高度差小于等于 1。 其每一个子树均为平衡二叉树。

为了计算平衡因子,我们要在节点中引入高度这一属性。在这里,我们把节点的高度定义为其左右子树的高度的最大值。

红黑树

Red-Black tree is a binary search tree in which every node is colored with either red or black.

the time complexity for operations such as insertion, deletion, and searching is always O(log n)

通过任意一条从根到叶子简单路径上颜色的约束、红黑树保证最长路径不超过最短路径的二倍、因而近似平衡(最短路径就是全黑节点、最长路径就是一个红节点一个黑节点)

  • 1.节点是红色或黑色
  • 2.根是黑色
  • 3.从根节点到叶子节点的所有路径上不能有2个连续的红色节点There are no two adjacent red nodes (A red node cannot have a red parent or red child)
  • 4.任一节点到其所有叶子节点,包含相同数量的黑色节点 Every path from a node (including root) to any of its descendants NULL nodes has the same number of black nodes.
  • 5.叶子节点(外部节点,空节点)都是*黑色,"*这里的叶子节点指的是最底层的空节点(外部节点),下图中的那些nul1节点才是叶子节点,nul节点的父节点在红黑树里不将其看作叶子节点

Comparison with[ AVL Tree]:
The AVL trees are more balanced compared to Red-Black Trees, but they may cause more rotations during insertion and deletion (RB-Tree最多只需要旋转3次实现复衡 ). So if your application involves frequent insertions and deletions, then Red-Black trees should be preferred. And if the insertions and deletions are less frequent and search is a more frequent operation, then AVL tree should be preferred over the Red-Black Tree.