2.4 作业

#include 

typedef struct t{
	char data;
	struct t *left;
	struct t *right;
}*tree;

tree tree_init();
tree tree_create();
void tree_frist_output(tree p);
void tree_mid_output(tree p);
void tree_last_output(tree p);
void tree_free(tree p);
int flag;

int main(int argc, const char *argv[])
{
	tree p=NULL;
	p=tree_create();
	while(1){
		printf("请选择遍历方式(1)先序,(2)中序,(3)后序,(0)退出:");
		scanf("%d",&flag);
		if(flag==1){
			tree_frist_output(p);
			puts("");
		}else if(flag==2){
			tree_mid_output(p);
			puts("");
		}else if(flag==3){
			tree_last_output(p);
			puts("");
		}else if(flag==0){
			break;
		}else{
			printf("输入有误,请重新输入!\n");
		}
	}
	tree_free(p);
	return 0;
}


//二叉树的初始化
tree tree_init(){
	tree p=(tree)malloc(sizeof(struct t));
	if(p==NULL){
		return NULL;
	}
	p->data=0;
	p->left=NULL;
	p->right=NULL;
	return p;
}

//创建一个二叉树
tree tree_create(){
	char element;
	tree 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(tree p){
	if(p==NULL){
		return;
	}
	printf("%c",p->data);
	tree_frist_output(p->left);
	tree_frist_output(p->right);
}

//中序遍历
void tree_mid_output(tree p){
	if(p==NULL){
		return;
	}
	tree_mid_output(p->left);
	printf("%c",p->data);
	tree_mid_output(p->right);
}

//后序遍历
void tree_last_output(tree p){
	if(p==NULL){
		return;
	}
	tree_last_output(p->left);
	tree_last_output(p->right);
	printf("%c",p->data);
}

//释放二叉树
void tree_free(tree p){
	if(p==NULL){
		return;
	}
	tree_free(p->left);
	tree_free(p->right);
	free(p);
	p=NULL;
}

结果:

2.4 作业_第1张图片

你可能感兴趣的:(c语言)