1. 程式人生 > >平衡查詢樹——2-3查詢樹——紅黑樹(1)

平衡查詢樹——2-3查詢樹——紅黑樹(1)

二叉查詢樹VS平衡查詢樹

Binary Search Tree possibilities

這裡寫圖片描述

Balanced Search Trees

這裡寫圖片描述

如何學 平衡查詢樹

為了保證之前學習的二分查詢樹BST的平衡性,解決在最壞情況時高度為N的情況,這裡有幾種平衡查詢樹:

  1. AVL

  2. 2-3 Search Trees

  3. Red-black BSTs ——紅黑二叉查詢樹

直接關注最重要的一種搜尋樹——紅黑樹,在SGI STL中紅黑樹是唯一實現的一種搜尋樹。

關於AVL,自行學習下思想就可以了,比如其中的幾個旋轉:

  1. 左左插入——左旋
  2. 右右插入——右旋
  3. 左右插入——左右旋
  4. 右左插入——右左旋

不過,要想充分理解紅黑樹。

首先,

得學習下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.

提醒:這裡,要理解定義中的nodekey,看一下上圖。

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——區域性變換

上面在說明插入操作時,已經將插入操作分為兩種:

  1. 針對2-node –to–> 3-node —- 不進行分裂
  2. 針對3-node –to–> 4-node —- 分裂

而,

將一個4-node分解為一顆2-3樹可能有6種情況:

  1. 根結點
  2. 2-node的左子樹
  3. 2-node的右子樹
  4. 3-node的左子樹
  5. 3-node的中子樹
  6. 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那樣,目前還不太可能…

不過,以後可能會去做。