平衡查詢樹——2-3查詢樹——紅黑樹(1)
二叉查詢樹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那樣,目前還不太可能…
不過,以後可能會去做。