#include <iostream>
#include <string>
#include "stdlib.h"
using namespace std;
typedef struct BiNode
{
char data;
struct BiNode *lchild;
struct BiNode *rchild;
}BiNode,*BiTree;
//采用分治法根据前序和后序序列构建二叉树
//1)取先序遍历序列的第一个值,用该值构造根结点,,然后在中序遍历序列中查找与该元素相等的值,这样就可以把序列分为三部分:左子树(如果有)、根结点和右子树(如果有)。
//
//2)将两个序列都分成三部分,这样就分别形成了根结点的左子树和右子树的先序遍历和后序遍历的序列。
//
//3)重复1)和2)步骤,直至所有结点都处理完就可以完整构成一颗二叉树了。
void Create_BiTree(BiTree&t, string presequence,string insequence)
{
//it is leaf
if (presequence.length()==0)
{
t=NULL;
return ;
}
//root
char rootNode=presequence[0];
//root location in inorder
int index=insequence.find(rootNode);
//left child sequence
string lchild_insequence=insequence.substr(0,index);
//right chlid sequence
string rchild_insequence=insequence.substr(index+1);
//left child length
int lchild_length=lchild_insequence.length();
//right child length
int rchild_length=rchild_insequence.length();
//left child presequence
string lchild_presequence=presequence.substr(1,lchild_length);
//right child presequence
string rchild_presequence=presequence.substr(1+lchild_length);
t=(BiTree)malloc(sizeof(BiNode));
if (t!=NULL)
{
t->data=rootNode;
Create_BiTree(t->lchild,lchild_presequence,lchild_insequence);
Create_BiTree(t->rchild,rchild_presequence,rchild_insequence);
}
}
void PreOrder(BiTree&t) //前序遍历
{
if (t!=NULL)
{
cout<<t->data;
PreOrder(t->lchild);
PreOrder(t->rchild);
}
}
void InOrder(BiTree&t) //中序遍历
{
if (t!=NULL)
{
InOrder(t->lchild);
cout<<t->data;
InOrder(t->rchild);
}
}
void PostOrder(BiTree&t){ //后序遍历
if (t!=NULL)
{
PostOrder(t->lchild);
PostOrder(t->rchild);
cout<<t->data;
}
}
int Depth(BiTree T) { //树的深度
int n,m;
if(T==NULL)
return 0;
else {
m=Depth(T->lchild);
n=Depth(T->rchild);
if(m>n)
return(m+1);
else
return(n+1);
}
}
int NodeCount(BiTree T) { //叶子结点数
if(T==NULL)
return 0;
else
return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}
int main()
{
BiTree a;
int height,num;
string presequence="ABDFGCEH";
string insequence="BFDGACEH";
Create_BiTree(a,presequence,insequence);
cout<<"按先序遍历法输出该二叉树的元素为:\n";
PreOrder(a);
cout<<"\n按中序遍历法输出该二叉树的元素为:\n";
InOrder(a);
cout<<"\n按后序遍历法输出该二叉树的元素为:\n";
PostOrder(a);
height=Depth(a);
num=NodeCount(a);
cout<<"\n该二叉树深度为:";
cout<<height<<endl;
cout<<"该二叉树结点数为:";
cout<<num;
return 0;
}