二叉树的四序遍历

#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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不关我事~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值