C++先序遍历与中序遍历生成二叉树 后序遍历与中序遍历生成二叉树
2016-05-04 16:06
507 查看
#include<iostream> #include<queue> #include<stack> using namespace std; template <class Type> class BinTreeNode; template <class Type> class BinTree; template <class Type> class BinTreeNode { friend class BinTree<Type>; public: BinTreeNode(Type d=Type(),BinTreeNode<Type> *left=0,BinTreeNode<Type> *right=0) :data(d),leftChild(left),rightChild(right) {} ~BinTreeNode(){} private: Type data; BinTreeNode<Type> *leftChild; BinTreeNode<Type> *rightChild; }; template<class Type> class BinTree { public: BinTree(Type ref,BinTreeNode<Type> *t=0) :root(t),refvalue(ref) {} ~BinTree(){} public: void CreateBinTree_Pre(char *VLR, char * LVR) { int n = strlen(VLR); CreateBinTree_Pre(root,VLR,LVR,n); } void CreateBinTree_Post(char *LRV, char *LVR) { int n = strlen(LRV); CreateBinTree_Post(root,LRV,LVR,n); } protected: void CreateBinTree_Post(BinTreeNode<Type> *& t, //后序遍历 char *LRV, char *LVR, int n) { if(n==0) return; else { int k = 0; while(LRV[n-1] != LVR[k]) k++; t = new BinTreeNode<Type>(LVR[k]); CreateBinTree_Post(t->leftChild,LRV,LVR,k); CreateBinTree_Post(t->rightChild,LRV+k,LVR+k+1,n-k-1); } } void CreateBinTree_Pre(BinTreeNode<Type> *& t, //先序遍历 char *VLR, char *LVR, int n) { if(n==0) return; else { int k = 0; while(VLR[0] != LVR[k]) {k++;} t = new BinTreeNode<Type>(LVR[k]); CreateBinTree_Pre(t->leftChild,VLR+1,LVR,k); CreateBinTree_Pre(t->rightChild,VLR+k+1,LVR+k+1,n-k-1); } } private: BinTreeNode<Type> *root; };
相关文章推荐
- Support For C++11/14/17 Features (Modern C++)
- STL学习笔记— —特殊容器stack
- C++智能指针 unique_ptr
- C++11 多线程编程---条件变量
- c++模版函数
- 堆排序的c语言实现
- 分解质因数(C++版)
- C语言malloc的使用浅谈
- c++ getline(),get()函数笔记
- c++ 子类调用父类构造方法 调用父类方法 类声明与实现分离
- C++中的引用和指针
- C语言(链表)
- 整数大数模拟 高精度加法 高精度减法 高精度乘法 高精度除法 c/c++ java
- c++ 八大排序算法
- c语言libcurl库的异步用法
- C语言(算法)
- C语言6(指针)
- C语言中指针变量使用时常见的几个问题
- 【C++】高精度代码运行时间( QueryPerformanceCounter )
- c++ 数据类型整理