丢了一次以前写的算法的文档和源代码,Ubuntu One不可靠啊!只好从头再写一遍。本文实现了一个树,不是二叉树,是N叉树。也就是允许一个节点拥有多个子节点。不是为了做题目糊弄人,所以内存管理不允许泄漏,用了C++11的shared_ptr。先看看调用代码:
- #include <iostream>
- #include <memory>
-
- 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函数初始化tree,放了一个根节点,然后加入三个子节点。view_root将四个节点数据遍历出来。tree这个类看上去可有可无,其实不然。今后会将查找,遍历等算法封装在tree类里面,方便使用。注意using的用法,是C++11的template aliases。
- using node_type = shared_ptr<node<int>>;