#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");
}
二叉树的遍历
最新推荐文章于 2024-01-27 15:36:29 发布