以前寫過的演算法筆記與原始碼丟了一整批——把資料放雲端同步,結果同步服務不可靠,只能重頭再寫一次。這篇要實作的不是二叉樹,而是 N 叉樹:允許一個節點擁有任意多個子節點。
既然是自己用的工具而非交作業的題目,就不能對記憶體管理睜一隻眼。這裡用 C++11 的 shared_ptr 讓節點生命週期自動管理,不必手動 delete,也不必擔心誰擁有可能誰釋放。
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
#include "tree.h"
using namespace freebird;
using node_type = shared_ptr<node<int>>;
using node_iterator = vector<shared_ptr<node<int>>>::iterator;
tree<node_type> t;
void init() {
node_type n1(new node<int>(1));
t.root(n1);
node_type n2(new node<int>(2));
node_type n3(new node<int>(3));
node_type n4(new node<int>(4));
n1->push_back(n2);
n1->push_back(n3);
n1->push_back(n4);
}
void view_root() {
node_type r = t.root();
cout << "the value of root:" << r->value() << endl;
node_iterator itor = r->begin();
node_iterator last = r->end();
for (; itor != last; ++itor) {
node_type cur_node = *itor;
cout << "the value of root's one child:"
<< cur_node->value() << endl;
}
}
int main(int args, char* argv[]) {
init();
view_root();
}
init() 建立一棵樹:先放進根節點,再掛上三個子節點。view_root() 則把根與它的孩子逐一印出,順便示範節點的迭代器介面 begin() / end()。
乍看之下 tree 這個類可有可無——節點自己就能記住孩子,何必多一層?理由在後續擴充:查找、遍歷(前序、後序、層序)、插入刪除、深度與平衡判斷這些演算法,都會被收進 tree 類裡,讓呼叫端只面對一個乾淨的介面,而不必直接操作節點內部。容器與演算法分層,是資料結構設計的基本紀律。
注意這兩行的寫法:
using node_type = shared_ptr<node<int>>;
using node_iterator = vector<shared_ptr<node<int>>>::iterator;
這是 C++11 引入的 template aliases,比傳統的 typedef 更清爽,而且支援模板參數——typedef 做不到「參數化別名」這件事。像 shared_ptr<node<int>> 這種層層嵌套的型別,一旦要換成 double 或 string,有別名就只需改一行。
骨架搭好之後,自然的延伸是:讓 node 支援任意型別的模板參數、為 tree 加上遍歷器與深度優先走訪、再補上「找第一個符合條件的子節點」這類常用查詢。若節點之間需要雙向導航(從子回頭找父),那時才需要引入 weak_ptr 存父節點,避免 shared_ptr 互指造成循環引用而無法釋放。