头文件:
#ifndef bitree_h
#define bitree_h
struct node
{
char data;
node *lchile, *rchile;
};
class bitree
{
public:
bitree(){root=great(root);}
~bitree(){release(root);}
void protree(){protree(root);}
void intree(){intree(root);}
void posttree(){posttree(root);}
private:
node *root;
node *great(node *bt);
void release(node *bt);
void protree(node *bt);
void intree(node *bt);
void posttree(node *bt);
};
#endif
函数定义:
#include<iostream>
#include"head.h"
using namespace std;
node *bitree::great(node *bt){
char ch;
cout<<"please input a tree's number:"<<endl;
cout<<"input '#' is null"<<endl;
cin>>ch;
if(ch=='#')return NULL;
else{
bt=new node;
bt->data=ch;
bt->lchile=great(bt->lchile);
bt->rchile=great(bt->rchile);
}
return bt;
}
void bitree::release(node *bt){
if(bt!=NULL){
release(bt->lchile);
release(bt->rchile);
delete bt;
}
}
void bitree::protree(node *bt){
if(bt==NULL)return;
else{
cout<<bt->data<<" ";
protree(bt->lchile);
protree(bt->rchile);
}
}
void bitree::intree(node *bt){
if(bt==NULL)return;
else{
intree(bt->lchile);
cout<<bt->data<<" ";
intree(bt->rchile);
}
}
void bitree::posttree(node *bt){
if(bt==NULL)return;
else{
posttree(bt->lchile);
posttree(bt->rchile);
cout<<bt->data<<" ";
}
}
main函数:
#include<iostream>
#include"head.h"
using namespace std;
void main(){
bitree t;
system("cls");
cout<<"---------------------------------------"<<endl;
cout<<" 1 前序遍历 2 中序遍历 "<<endl;
cout<<" 3 前序遍历 0 退出 "<<endl;
cout<<"---------------------------------------"<<endl;
int a;
cout<<"选择其中一项进行:";
cin>>a;
while(a!=0){
switch(a){
case 1:cout<<"--------前序遍历-------"<<endl;
t.protree();
cout<<endl;
break;
case 2: cout<<"--------中序遍历-------"<<endl;
t.intree();
cout<<endl;
break;
case 3:cout<<"--------后序遍历-------"<<endl;
t.posttree();
cout<<endl;
break;
default: cout<<endl;
cout<<"请输入正确的编号"<<endl;
break;
}
system("pause");
system("cls");
cout<<"---------------------------------------"<<endl;
cout<<" 1 前序遍历 2 中序遍历 "<<endl;
cout<<" 3 前序遍历 0 退出 "<<endl;
cout<<"---------------------------------------"<<endl;
cout<<"选择其中一项进行:";
cin>>a;
}
}