N叉树一 基本实现

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


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

现在看看tree.h中的实现。

#ifndef _TREE_H
#define _TREE_H

#include <vector>
#include <memory>

namespace freebird {

  template<typename T>
    class node{
  public:
  node(T value):value_(value){
    }



    /**
     * insert child node to the end
     */
    void push_back(std::shared_ptr<node<T>> child){
      children_.push_back(child);
    }

    typedef typename std::vector<shared_ptr<node<T>>>::iterator iterator_type;

    void insert(iterator_type pos,std::shared_ptr<node<T> > 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<shared_ptr<node<T>>> children_;
  };



  template<typename T>
    class tree {
  public:
    tree<T>(){
    }

    void root(T node){
      root_ = node;
    }

    T root() {
      return root_;
    }
    
  private:
    T root_;
  };
}

#endif

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

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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值