二叉查找树VS平衡查找树
Binary Search Tree possibilities
Balanced Search Trees
如何学 平衡查找树
为了保证之前学习的二分查找树BST的平衡性,解决在最坏情况时高度为N的情况,这里有几种平衡查找树:
AVL
2-3 Search Trees
Red-black BSTs ——红黑二叉查找树
直接关注最重要的一种搜索树——红黑树,在SGI STL中红黑树是唯一实现的一种搜寻树。
关于AVL,自行学习下思想就可以了,比如其中的几个旋转:
- 左左插入——左旋
- 右右插入——右旋
- 左右插入——左右旋
- 右左插入——右左旋
不过,要想充分理解红黑树。
首先,
得学习下2-3 Search Trees的思想,可以这样说,红黑树就是利用一种更为简单的数据结构来表达和实现2-3 Search Trees
这样,
才能在理解代码量较小实现的红黑树。
所以,
接下来先要打一下2-3 Search Trees的基础。
2-3 Search Trees ?
Definition. A 2-3 search tree is a tree that is either empty or
■ A 2-node, with one key (and associated value) and two links,
a left link to a 2-3 search tree with smaller keys, and a right
link to a 2-3 search tree with larger keys
■ A 3-node, with two keys (and associated values) and three
links, a left link to a 2-3 search tree with smaller keys, a mid- dle link to a 2-3 search tree with keys between the node’s keys, and a right link to a 2-3 search tree with larger keys
As usual, we refer to a link to an empty tree as a null link.
提醒:这里,要理解定义中的node和key,看一下上图。
Search
Insert
2-3查找树中的插入,分为以下1+3种情况:
这一种主要是针对2-node
Insert into a 2-node
下面3种主要针对3-node
Insert into a tree consisting of a single 3-node
Insert into a 3-node whose parent is a 2-node
Insert into a 3-node whose parent is a 3-node
可以看到,在保持2-3查找树的性质,在执行插入操作后,可能会进行分裂操作,上面随插入进行的分裂都可以比较容易的理解。
但是,
还有一种情况,当随着从下往上局部分裂后到达根节点,根节点已经有2-key(也就是3-node),并从子结点上升来了一个key(也就是执行了插入),“爆”了怎么办?
Splitting the root
Local transformations——局部变换
上面在说明插入操作时,已经将插入操作分为两种:
- 针对2-node –to–> 3-node —- 不进行分裂
- 针对3-node –to–> 4-node —- 分裂
而,
将一个4-node分解为一颗2-3树可能有6种情况:
- 根结点
- 2-node的左子树
- 2-node的右子树
- 3-node的左子树
- 3-node的中子树
- 3-node的右子树
Global properties ——全局性质
上面所示的局部变黄不会影响树的全局性质(有序性和平衡性):任意空链接到根结点的路径长度都是相等的。
These local transformations preserve the global properties that the tree is ordered and perfectly balanced: the number of links on the path from the root to any null link is the same.
If the length of every path from a root to a null link is h before the transformation, then it is h after the transformation. Each transformation preserves this property, even while splitting the 4-node into two 2-nodes and while changing the parent from a 2-node to a 3-node or from a 3-node into a temporary 4-node. When the root splits into three 2-nodes, the length of every path from the root to a null link increases by 1.
只有根结点分裂时,树的深度才会加1
完整构造对比
2-3查找树两个完整构造的例子
左:普通构造
右:同一组key,按升序插入
二叉查找树——非平衡
如果时二叉查找树,构造中就会出现worst case:
总结
之后会根据自己所学来介绍红黑树,将代码贴一下。
当然,要想像SGI STL那样,目前还不太可能…
不过,以后可能会去做。