include <stdlib.h>
include
/(1)创建一颗二叉树
,用递归方法实现对其进行先序、
中序和后序遍历的操作
/
//创建二叉树结构体
typedef struct Node
{
char data;
struct Node LChild;
struct Node RChild;
}BiTNode,BiTree;
using namespace std;
//结构体初始化
void init(BiTree bt)
{
bt=(BiTree)malloc(sizeof(BiTNode));
(bt)->LChild=NULL;
(*bt)->RChild=NULL;
}
//建立二叉树
void CreateBiTree(BiTree bt)
{
char ch;
cin>>ch;
if(ch=='#') bt=NULL;
else
{
bt=(BiTree)malloc(sizeof(BiTNode));
(bt)->data=ch;
CreateBiTree(&((bt)->LChild));
CreateBiTree(&((bt)->RChild));
}
}
//先序遍历二叉树
void PreOrder(BiTree bt)
{
if(bt!=NULL)
{
printf("%c",bt->data);
PreOrder(bt->LChild);
PreOrder(bt->RChild);
}
}
//中序遍历二叉树
void inOrder(BiTree bt)
{
if(bt!=NULL)
{
inOrder(bt->LChild);
printf("%c",bt->data);
inOrder(bt->RChild);
}
}
//后序遍历二叉树
void PostOrder(BiTree bt)
{
if(bt!=NULL)
{
PostOrder(bt->LChild);
PostOrder(bt->RChild);
printf("%c",bt->data);
}
}
int main()
{
BiTree bt;
init(&bt);
int i;
while(1)
{
cout<<"输入1:创建二叉树"<<endl;
cout<<"输入2:先序遍历二叉树"<<endl;
cout<<"输入3:中序遍历二叉树"<<endl;
cout<<"输入4:后序遍历二叉树"<<endl;
cout<<"输入0:退出"<<endl;
cout<<"请输入要执行的操作"<<endl;
cin>>i;
switch(i)
{
case 1:
cout<<"请输入数据"<<endl;
CreateBiTree(&bt);
break;
case 2: PreOrder(bt); cout<<endl; break; case 3: inOrder(bt); cout<<endl; break; case 4: PostOrder(bt); cout<<endl; break; case 0: break; } if(i==0) break; }
}
来源:https://www.cnblogs.com/cyp-00-111/p/10781080.html