不说废话了,直接上代码
#include<iostream>
#define MAXSIZE 100
using namespace std;
struct node
{
struct node *lchlid;
struct node *rchlid;
char date;
};
void BulidTree(struct node *&T)
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T = new struct node;//申请新的空间
T->date=ch;
BulidTree(T->lchlid);
BulidTree(T->rchlid);
}
}
void Preorder(struct node *&T)//先序遍历:访问根节点,先序遍历左子树,先序遍历右子树
{
if(T)
{
cout<<T->date<<" ";
Preorder(T->lchlid);
Preorder(T->rchlid);
}
}
void Midorder(struct node *&T)//中序遍历:中序遍历左子树,访问根节点,中序遍历右子树
{
if(T)
{
Midorder(T->lchlid);
cout<<T->date<<" ";
Midorder(T->rchlid);
}
}
void Postorder(struct node *&T)//后续遍历:后续遍历左子树,后续遍历右子树,访问根节点
{
if(T)
{
Midorder(T->lchlid);
Midorder(T->rchlid);
cout<<T->date<<" ";
}
}
int main()
{
struct node *T;
BulidTree(T);
cout<<"Get Tree"<<endl;
cout<<"Preorder"<<endl;
Preorder(T);cout<<endl;
cout<<"Midorder"<<endl;
Midorder(T);cout<<endl;
cout<<"Postorder"<<endl;
Postorder(T);cout<<endl;
return 0;
}