数据结构——二叉树的前,中,后遍历

#include<stdio.h>
#include<stdlib.h>
#define maxsize 30 
typedef char datatype;
typedef struct binode{
	datatype data;
	struct binode *lchild,*rchild;
}binode;

void preorder(binode *root){
	if(root==NULL)	return;
	else{
		printf("%c",root->data);		//前序遍历 
		preorder(root->lchild);
		preorder(root->rchild);
	}
}

void inorder(binode *root){
	if(root==NULL)	return;
	else{
		inorder(root->lchild);
		printf("%c",root->data);		//中序遍历 
		inorder(root->rchild);
	}
}

void postorder(binode *root){
	if(root==NULL)	return;
	else{
		postorder(root->lchild);		//后序遍历 
		postorder(root->rchild);
		printf("%c",root->data);
	}
}

void levelorder(binode *root){
	binode *q=NULL,*Q[maxsize];
	int front=-1;
	int rear=-1;
	if(root==NULL)	return;					//层序遍历 
	Q[++rear]=root;
	while(front!=rear){
		q=Q[++front];
		printf("%c",q->data);
		if(q->lchild!=NULL)	Q[++rear]=q->lchild;
		if(q->rchild!=NULL)	Q[++rear]=q->rchild;
	}
}

binode *creatbitree(binode *root){
	char ch;
	scanf("%c",&ch);
	if(ch=='#')	return root=NULL;
	else{
		root=(binode *)malloc(sizeof(binode));		//前序遍历方式创建“二叉树” 
		root->data=ch;
		root->lchild=creatbitree(root->lchild);
		root->rchild=creatbitree(root->rchild);
	}
	return root;
}

void destroybitree(binode *root){
	if(root==NULL)	return;
	else{
		destroybitree(root->lchild);		//销毁二叉树 
		destroybitree(root->rchild);
		free(root);
		
	}
}

int main(){
	binode *root=NULL;
	root=creatbitree(root);
	printf("the root is :%c",root->data);
	printf("\nthe preorder is:");
	preorder(root);
	printf("\nthe inorder is:");
	inorder(root);
	printf("\nthe postorder is:");
	postorder(root);
	printf("\nthe levelorder is:");
	levelorder(root);
	destroybitree(root);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值