丢了一次以前写的算法的文档和源代码,Ubuntu One不可靠啊!只好从头再写一遍。
本文实现了一个树,不是二叉树,是N叉树。也就是允许一个节点拥有多个子节点。
不是为了做题目糊弄人,所以内存管理不允许泄漏,用了C++11的shared_ptr。先看看调用代码:
#include
#include
using namespace std;
#include "tree.h"
using namespace freebird;
using node_type = shared_ptr>;
using node_iterator = vector>>::iterator;
tree t;
void init(){
node_type n1(new node(1));
t.root(n1);
node_type n2(new node(2));
node_type n3(new node(3));
node_type n4(new node(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:"<value()<begin();
node_iterator last = r->end();
for(;itor!=last;++itor){
node_type cur_node = *itor;
cout<<"the value of root's one child:"<value()<
view_root将四个节点数据遍历出来。
tree这个类看上去可有可无,其实不然。今后会将查找,遍历等算法封装在tree类里面,方便使用。
注意using的用法,是C++11的template aliases。
using node_type = shared_ptr>;
现在看看tree.h中的实现。
#ifndef _TREE_H
#define _TREE_H
#include
#include
namespace freebird {
template
class node{
public:
node(T value):value_(value){
}
/**
* insert child node to the end
*/
void push_back(std::shared_ptr> child){
children_.push_back(child);
}
typedef typename std::vector>>::iterator iterator_type;
void insert(iterator_type pos,std::shared_ptr > child){
children_.insert(pos,child);
}
T value() const {
return value_;
}
/**
* iterator to the first child
*/
iterator_type begin(){
return children_.begin();
}
/**
* Get the end iterator of children
*/
iterator_type end(){
return children_.end();
}
private:
T value_;
std::vector>> children_;
};
template
class tree {
public:
tree(){
}
void root(T node){
root_ = node;
}
T root() {
return root_;
}
private:
T root_;
};
}
#endif
实现还是挺简单的,用了一个vector,里面存放了shared_ptr