歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> N叉樹一 基本實現

N叉樹一 基本實現

日期:2017/3/1 10:19:32   编辑:Linux編程

丟了一次以前寫的算法的文檔和源代碼,Ubuntu One不可靠啊!只好從頭再寫一遍。

本文實現了一個樹,不是二叉樹,是N叉樹。也就是允許一個節點擁有多個子節點。

不是為了做題目糊弄人,所以內存管理不允許洩漏,用了C++11的shared_ptr。先看看調用代碼:

  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4. #include "tree.h"
  5. using namespace freebird;
  6. using node_type = shared_ptr<node<int>>;
  7. using node_iterator = vector<shared_ptr<node<int>>>::iterator;
  8. tree<node_type> t;
  9. void init(){
  10. node_type n1(new node<int>(1));
  11. t.root(n1);
  12. node_type n2(new node<int>(2));
  13. node_type n3(new node<int>(3));
  14. node_type n4(new node<int>(4));
  15. n1->push_back(n2);
  16. n1->push_back(n3);
  17. n1->push_back(n4);
  18. }
  19. void view_root(){
  20. node_type r = t.root();
  21. cout<<"the value of root:"<<r->value()<<endl;
  22. node_iterator itor = r->begin();
  23. node_iterator last = r->end();
  24. for(;itor!=last;++itor){
  25. node_type cur_node = *itor;
  26. cout<<"the value of root's one child:"<<cur_node->value()<<endl;
  27. }
  28. }
  29. int main(int args,char* argv[]){
  30. init();
  31. view_root();
  32. }
init函數初始化tree,放了一個根節點,然後加入三個子節點。

view_root將四個節點數據遍歷出來。

tree這個類看上去可有可無,其實不然。今後會將查找,遍歷等算法封裝在tree類裡面,方便使用。

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

  1. using node_type = shared_ptr<node<int>>;
Copyright © Linux教程網 All Rights Reserved