N叉树一 基本实现

丢了一次以前写的算法的文档和源代码,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()<

init函数初始化tree,放了一个根节点,然后加入三个子节点。

view_root将四个节点数据遍历出来。

tree这个类看上去可有可无,其实不然。今后会将查找,遍历等算法封装在tree类里面,方便使用。

注意using的用法,是C++11的template aliases。

using node_type = shared_ptr>;


我用的是GCC4.7.0,Ubuntu 12.04,CMake.

现在看看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

shared_ptr就在memory头文件中,不再需要加入boost库。

实现还是挺简单的,用了一个vector,里面存放了shared_ptr>,因此删除的时候不要手动delete。只是小心不要在树里面节点形成回路,那是shared_ptr最忌讳的。‘




你可能感兴趣的:(N叉树一 基本实现)