Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

B-Tree 的 C++ 實作解析

本文先簡要說明 B 樹的性質,再透過 C++ 類別設計展示其節點組織與操作介面。

B 樹的性質

以 M 表示 B 樹的階數、L 表示葉子節點的最大元素個數(性質整理自《數據結構與問題求解 C++ 版》第19章):

1、數據項保存在葉子中;
2、非葉子節點具有 M-1 個鍵引導查找,鍵 i 代表子樹 i+1 中最小的鍵;
3、根要麼是葉子,要麼有 2~M 個孩子;
4、所有非葉子節點(根除外)具有 [M/2]~M 個孩子;
5、所有葉子在同一深度,且對某一葉子具有 [L/2]~L 個數據項。

插入與刪除的分裂、合併

插入時,若某葉子元素已達 L 個,就需要分裂,而葉子分裂也可能引起父節點分裂,效果可能逐層往上,直到根分裂產生新根才停止(這種情況很少見)。刪除時,可能使葉子元素數目不滿足規則5,此時需合併葉子,而合併也可能造成父節點合併,向上傳遞直到根的孩子數減為 0、樹高減一才停止(同樣罕見)。

C++ 類別設計

#include<iostream>
using std::cout;
using std::endl;
using std::ostream;
//定義 B 樹的階數
#define M 4
#define L 3
class BTree
{
private:
int child_size;  //非葉子節點時表示子節點個數
int elem_size;    //葉子節點時表示所含元素個數
bool is_leaf;
BTree* parent;
BTree* root;
/*
葉子節點使用 elem_data;非葉子節點則用 child_list 保存子節點指標,並用 index_key 對應第二條性質
*/
union{     
struct{
BTree* child_list[M];
int index_key[M-1];
};
int elem_data[L];
};
public:
BTree();
void insert(int);  //插入一個元素
void insert(int*,int);  //插入一個陣列
~BTree();
void remove(int);
BTree* getRoot();
friend ostream& operator<<(ostream& os,BTree);
friend bool check_tree(BTree* root);
private:
void node_break( BTree&, BTree&); //插入引起分裂時使用
void node_merge(BTree&); //刪除引起葉子合併時使用
void array_insert(int* array,int data, int size); //有序陣列插入
int array_remove(int* array,int data, int size); //有序陣列刪除
int get_min_value(const BTree&); //取得某子樹最小值
int get_size(const BTree&); //回傳節點元素數或子樹數
};

值得注意的技巧是:以 union 讓葉子節點與非葉子節點共用記憶體空間,依 is_leaf 決定使用 elem_data 或 child_list 與 index_key,兼顧了空間效率與查找效率。

Copyright © Linux教程網 All Rights Reserved