非递归遍历二叉树(前序,中序,后序遍历)

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct Node
{
    int data;
    struct Node *Lchild;
    struct Node *Rchild;
}BTNode, *BTtree;
typedef struct
{
    BTtree date[MAX];
    int top;
}Sstack;

BTtree creat();//创建二叉树
Sstack Init_Sstack();//初始化栈
int  Push(Sstack *s, BTtree x);//入栈
BTtree pop(Sstack *s, BTtree e);//出栈
void BeforeOrder(BTtree L);//前序遍历
void midOrder(BTtree L);//中序遍历
void BackOrder(BTtree L);//后序遍历

int main(void)
{
    BTtree s;
    s = creat();
    BeforeOrder(s);
    printf("\n");
    midOrder(s);
    printf("\n");
    BackOrder(s);
    return 0;
}
Sstack Init_Sstack()
{
    Sstack *s;
    s = (Sstack*)malloc(sizeof(Sstack));
    s->top = -1;
    return *s;
}
int Empty(Sstack s)
{
    if (s.top == -1)
        return 1;
    else
        return 0;
}
BTtree pop(Sstack *s, BTtree e)
{
    if (Empty(*s))
        return 0;
    else {
        e = s->date[s->top];
        s->top--;
        return e;
    }

}
int  Push(Sstack *s, BTtree x)
{
    if (s->top == MAX - 1)
        return 0;
    else {
        s->top++;
        s->date[s->top] = x;
        return 1;
    }
}

BTtree top(Sstack *s)
{
    if (Empty(*s))
        return 0;
    else {
        return s->date[s->top];
    }
}
BTtree creat()
{
    char ch;
    BTtree s;
    ch = getchar();
    if (ch == '#')
        s = NULL;
    else
    {
        s = (BTtree)malloc(sizeof(BTNode));
        s->data = ch;
        s->Lchild = creat();
        s->Rchild = creat();
    }
    return s;
}
void BeforeOrder(BTtree L){       //前序遍历
    Sstack s;
    BTtree p;
    s =Init_Sstack();
    p=L;
    while(p!=NULL||!Empty(s)) {
        while(p!=NULL){
            printf("%c", p->data);
            Push(&s,p);
            p=p->Lchild;
        }
        if(!Empty(s)){
            p=pop(&s,p);
            p=p->Rchild;
        }
    }
}
void midOrder(BTtree L){      //中序遍历
    Sstack s;
    BTtree p;
    s=Init_Sstack();
    p=L;
    while(p!=NULL||!Empty(s)){
        while(p!=NULL){
            Push(&s,p);
            p=p->Lchild;
        }
        if(!Empty(s)){
            p=pop(&s,p);
            printf("%c",p->data);
            p=p->Rchild;
        }
    }
}
void BackOrder(BTtree L)          //后序遍历
{
    Sstack s;
    BTtree p,q;
    s = Init_Sstack();p = L;q = NULL;
    while (p != NULL||!Empty(s))
    {
        while (p != NULL)
        {
            Push(&s, p);
            p = p->Lchild;
        }
        if (!Empty(s))
        {
            p = top(&s);
            if (p->Rchild == NULL || p->Rchild == q)
            {
                p = pop(&s, p);
                printf("%c", p->data);
                q = p;
                p = NULL;
            }
            else
            p = p->Rchild;
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值