您的位置:首页 > 编程语言 > C语言/C++

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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: