1.代码
#include<iostream>
#define Maxsize 10000
using namespace std;
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
void CreateBtree(BTNode *&b,char *str);//创建二叉树
void PreOrder(BTNode *b);//先序遍历输出二叉树
void InOrder(BTNode *b);//中序遍历输出二叉树
void PostOrder(BTNode *b);//后序遍历输出二叉树
void DestroyBtree(BTNode *&b);//销毁二叉树
int main()
{
BTNode *b;
char str[Maxsize];
cin>>str;
CreateBtree(b,str);
cout<<"先序遍历:";
PreOrder(b);
cout<<endl;
cout<<"中序遍历:";
InOrder(b);
cout<<endl;
cout<<"后序遍历:";
PostOrder(b);
DestroyBtree(b);
return 0;
}
void CreateBtree(BTNode *&b,char *str)//创建二叉树
{
BTNode *St[Maxsize],*p;
int k,j=0,top=-1;
char ch;
b=NULL;
ch=str[j];
while(ch!='\0')
{
switch(ch)
{
case '(':top++;St[top]=p;k=1;break;
case ')':top--;break;
case ',':k=2;break;
default:p=new BTNode;
p->data=ch;
p->lchild=p->rchild=NULL;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
void PreOrder(BTNode *b)//先序遍历输出二叉树
{
if(b!=NULL)
{
cout<<b->data;
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
void InOrder(BTNode *b)//中序遍历输出二叉树
{
if(b!=NULL)
{
InOrder(b->lchild);
cout<<b->data;
InOrder(b->rchild);
}
}
void PostOrder(BTNode *b)//后序遍历输出二叉树
{
if(b!=NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
cout<<b->data;
}
}
void DestroyBtree(BTNode *&b)//销毁二叉树
{
if(b!=NULL)
{
DestroyBtree(b->lchild);
DestroyBtree(b->rchild);
delete(b);
}
}
2.运行结果截图