代码说明
- C & C++
- 结构体变量表示节点
- 使用STL中的stack简化操作
#include<cstdio>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<stack>
using namespace std;
#define N 100
typedef struct mybinarytree
{
char data;
struct mybinarytree *left, *right;
}BT;
BT *createBT(char *pre,char *in,int k);
void showTree(BT *T);
void preVisit(BT *T);
void inVisit(BT *T);
void postVisit(BT *T);
int main(void)
{
BT *T;
char pre[]="ABDEFC";
char in[]= "BEDFAC";
int k=strlen(pre);
T=createBT(pre,in,k);
cout<<"以括号的形式显示二叉树:\n";
showTree(T);
cout<<"\n\n先序遍历:\n";
preVisit(T);
cout<<"\n\n中序遍历:\n";
inVisit(T);
cout<<"\n\n后序遍历:\n";
postVisit(T);
cout<<endl<<endl;
return 0;
}
BT *createBT(char *pre,char *in,int k)
{
int i,pos;
char data;
BT *p;
if(k==0)
return NULL;
else{
data=pre[0];
p=(BT *)malloc(sizeof(BT));
p->data=data;
for(i=0;i<k && in[i]!=data;i++);
pos=i;
p->left=createBT(pre+1,in,pos);
p->right=createBT(pre+pos+1,in+pos+1,k-pos-1);
return p;
}
}
void showTree(BT *T)
{
if(T)
{
cout<<T->data;
if(T->left || T->right)
{
cout<<"(";
showTree(T->left);
cout<<",";
showTree(T->right);
cout<<")";
}
}
}
void preVisit(BT *T)
{
stack<BT *> t;
BT *p;
if(!T)
{
cout<<"栈为空.\n";
return;
}
t.push(T);
while(!t.empty())
{
p=t.top();
cout<<p->data;
t.pop();
if(p->right)
t.push(p->right);
if(p->left)
t.push(p->left);
}
}
void inVisit(BT *T)
{
stack<BT *> t;
BT *p,*q;
q=T;
while(!t.empty()||q)
{
while (q)
{
t.push(q);
q=q->left;
}
p=t.top();
cout<<p->data;
t.pop();
q=p->right;
}
}
void postVisit(BT *T)
{
stack<BT *> t;
BT *p,*q,*pre;
q=T;
do{
while(q)
{
t.push(q);
q=q->left;
}
pre=NULL;
while(!t.empty())
{
p=t.top();
if(p->right==pre)
{
cout<<p->data;
t.pop();
pre=p;
}
else{
q=p->right;
break;
}
}
}while(!t.empty());
}
运行结果