#include<iostream>
using namespace std;
#define QueueSize 50
#define MaxSize 100
typedef char ElemType;
typedef struct BiNode{
ElemType data;
BiNode *lchild,*rchild;
}BiNode;
typedef struct element{
BiNode *ptr;
int flag;
}element;
void preorder(BiNode *root){
if(root==NULL)return;
else{
cout<<root->data;
preorder(root->lchild);
preorder(root->rchild);
}
}
void creat(BiNode *&root){
ElemType ch;
cin>>ch;
if(ch=='#')root=NULL;
else{
root=new BiNode;
root->data=ch;
creat(root->lchild);
creat(root->rchild);
}
}
void CreateBiTree1(BiNode *&boot,char *str)
{
BiNode *s[MaxSize],*p=NULL;
int top=-1,k,j=0;
char ch;
boot=NULL;
ch=str[j];
while (ch!='\0')
{
switch(ch)
{
case '(':top++;s[top]=p;k=1; break;
case ')':top--;break;
case ',':k=2; break;
default:p=new BiNode;
p->data=ch;p->lchild=p->rchild=NULL;
if (boot==NULL)
boot=p;
else
{
switch(k)
{
case 1:s[top]->lchild=p;break;
case 2:s[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
void DispBiTree(BiNode *root) {
if (root!=NULL)
{
cout<<root->data;
if (root->lchild!=NULL || root->rchild!=NULL)
{
cout<<"(";
DispBiTree(root->lchild);
if (root->rchild!=NULL) cout<<",";
DispBiTree(root->rchild);
cout<<")";
}
}
}
void postorder(BiNode *root){
element s[20];
int top=-1;
BiNode *p=root;
while(p!=NULL||top!=-1){
while(p!=NULL){
top++;
s[top].ptr=p;
s[top].flag=0;
p=p->lchild;
}
if(top!=-1){
if(s[top].flag==0){
p=s[top].ptr;
s[top].flag=1;
p=p->rchild;
}
else cout<<s[top--].ptr->data <<" ";
}
}
}
int main(){
BiNode *b;
CreateBiTree1(b,"A(B(D(,G)),C(E,F))");
cout<<"前序遍历 ";
preorder(b);
cout<<endl;
cout<<"广义形式 ";
DispBiTree(b);
cout<<endl;
cout<<"后序遍历 " ;
postorder(b);
cout<<endl;
cout<<"层次输出二叉树";
}
|