#include<stdio.h>
#include<stdlib.h>
typedef char elep;
#define MAXSIZE 10005
struct btree {
btree *l,*r;
elep data;
};
struct stack{
btree *base,*top;
elep length,Size;
};
stack create_Stack(){
stack stack1;
stack1.base=(btree*)malloc(sizeof(btree)*MAXSIZE);
stack1.top=stack1.base;
stack1.length=0;
stack1.Size=MAXSIZE;
return stack1;
}
void stack_Push(stack &stack1,btree *t){
if(stack1.top-stack1.base!=stack1.Size){
stack1.top=t;
stack1.top++;
stack1.length++;
}
}
void stack_Pop(stack &stack1){
stack1.top--;
stack1.length--;
}
btree* create() {
btree* t=(btree*)malloc(sizeof(btree));
char x;
scanf("%c",&x);
if(x=='#') {
t=NULL;
} else {
t->data=x;
t->l=create();
t->r=create();
}
return t;
}
void visit(btree *t) {
printf("%2c",t->data);
}
void cread(btree * T) {
if(T) {
btree * queue[MAXSIZE], * p;
int front,rear;
front=rear=0;
rear=(rear+1)%MAXSIZE;
queue[rear]=T;
while(front!=rear) {
front=(front+1)%MAXSIZE;
p=queue[front];
printf("%2c",p->data);
if(p->l) {
rear=(rear+1)%MAXSIZE;
queue[rear]=p->l;
}
if(p->r) {
rear=(rear+1)%MAXSIZE;
queue[rear]=p->r;
}
}
}
}
void xread(btree *t) {
if(t==NULL) {
return;
}
visit(t);
xread(t->l);
xread(t->r);
}
void zread(btree *t) {
if(t==NULL) {
return;
}
zread(t->l);
visit(t);
zread(t->r);
}
void hread(btree *t) {
if(t==NULL) {
return;
}
hread(t->l);
hread(t->r);
visit(t);
}
int main() {
btree *t=create();
printf("层次遍历:");
cread(t);
printf("\n\n");
printf("先序遍历:");
xread(t);
printf("\n\n");
printf("中序遍历:");
zread(t);
printf("\n\n");
printf("后序遍历:");
hread(t);
printf("\n");
}
二叉树的四序遍历
最新推荐文章于 2023-07-14 17:55:45 发布