二叉树的遍历

#include<stdio.h>
#include<malloc.h>
#define Maxsize 100
typedef char dataType;
struct TreeNode{
	dataType data;
	TreeNode *left,*right;
};
void CreateTree(TreeNode *&t,dataType x){
	dataType d;
	scanf("%c ",&d);
	if(d == x){
		t = NULL;
	}else{
		t = (TreeNode*)malloc(sizeof(TreeNode));
		t->data = d;
		CreateTree(t->left,x);
		CreateTree(t->right,x);
	}	
}
//先序遍历二叉树 
void Perorder(TreeNode *t){
	if(t){
	printf("%c ",t->data);
	Perorder(t->left);
	Perorder(t->right);
	}
}
//中序遍历二叉树
void Inorder(TreeNode *t){
	if(t){
	Inorder(t->left);
	printf("%c ",t->data);
	Inorder(t->right);
	} 
}
//后序遍历二叉树
void Postorder(TreeNode *t){
	if(t){
	Postorder(t->left);
	Postorder(t->right);
	printf("%c ",t->data);
	} 
} 
//层次序遍历二叉树
void Leverorder(TreeNode *t){
	TreeNode *q[Maxsize];
	int front = 0,rear = 0;
	TreeNode *p;
	if(t == NULL) return;
	q[rear] = t;
	rear = (rear+1) % Maxsize;
	while(front!=rear){
		p = q[front];
		front = (front+1) % Maxsize;
		printf("%c ",p->data);
		if(p->left){
			q[rear] = p->left;
			rear = (rear+1) % Maxsize;
		} 
		if(p->right){
			q[rear] = p->right;
			rear = (rear+1) % Maxsize;
		}
	}
} 
int main()
{
	TreeNode *t;
	CreateTree(t,'#');
	printf("先序遍历:");
	Perorder(t);
	printf("\n");
	printf("中序遍历:");
	Inorder(t);
	printf("\n");
	printf("后序遍历:");
	Postorder(t);
	printf("\n");
	printf("层序遍历:");
	Leverorder(t);
	printf("\n");			
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值