#include <myhead.h>
typedef struct tree{
char data;
struct t *left;
struct t *right;
}*t_p;
t_p tree_init();
t_p tree_create();
void tree_frist_output(t_p p);
void tree_mid_output(t_p p);
void tree_last_output(t_p p);
void tree_free(t_p p);
int flag=0;
int main(int argc, const char *argv[])
{
t_p p=NULL;
p=tree_create();
while(1){
printf("请选择遍历方式(0)先序,(1)中序,(2)后序:");
scanf("%d",&flag);
if(flag==0){
tree_frist_output(p);
puts("");
}else if(flag==1){
tree_mid_output(p);
puts("");
}else if(flag==2){
tree_last_output(p);
puts("");
}else{
printf("输入错误,请重新输入!\n");
}
}
tree_free(p);
return 0;
}
//二叉树的初始化
t_p tree_init(){
t_p p=(t_p)malloc(sizeof(struct t));
if(p==NULL){
return NULL;
}
p->data=0;
p->left=NULL;
p->right=NULL;
return p;
}
//创建二叉树
t_p tree_create(){
char element;
t_p p=tree_init();
printf("请输入字符:");
scanf("%c",&element);
getchar();
if(element=='#'){
return NULL;
}
p->data=element;
p->left=tree_create();
p->right=tree_create();
return p;
}
//先序遍历
void tree_frist_output(t_p p){
if(p==NULL){
return;
}
printf("%c",p->data);
tree_frist_output(p->left);
tree_frist_output(p->right);
}
//中序遍历
void tree_mid_output(t_p p){
if(p==NULL){
return;
}
tree_mid_output(p->left);
printf("%c",p->data);
tree_mid_output(p->right);
}
//后序遍历
void tree_last_output(t_p p){
if(p==NULL){
return;
}
tree_last_output(p->left);
tree_last_output(p->right);
printf("%c",p->data);
}
//释放二叉树
void tree_free(t_p p){
if(p==NULL){
return;
}
tree_free(p->left);
tree_free(p->right);
free(p);
p=NULL;
}
编写程序实现二叉树的创建,三种遍历自己销毁
最新推荐文章于 2024-08-24 15:52:22 发布