C语言实现二叉树遍历

#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
typedef struct node
{
    datatype data;
    struct node *lchild,*rchild;
}bintnode;
typedef bintnode * bintree;
bintree root;

bintree createtree()
{
    char ch;
    bintree t;
    if((ch=getchar())=='#')
    {
        t=NULL;
    }
    else
    {
        t=(bintnode*)malloc(sizeof(bintree));
        t->data=ch;
        t->lchild=createtree();
        t->rchild=createtree();
    }
}

typedef struct stack
{
    bintree data[100];
    int tag[100];
    int top;
}seq;

void push(seq *s,bintree t)
{
    s->data[s->top]=t;
    s->top++;
}
bintree pop(seq *s)
{
    if(s->top!=0)
    {
        s->top--;
        return s->data[s->top];
    }
    else
    {
        return NULL;
    }
}
//非递归前序遍历 
void pre(bintree t)
{
    seq s;
    s.top=0;
    while(t||(s.top!=0))
    {
        if(t)
        {
            printf("%c",t->data);
            push(&s,t);
            t=t->lchild;
        }
        else
        {
            pop(&s);
            t=t->rchild;
        }
    }
}
//中序遍历 
void  mid(bintree t)
{
    seq s;
    s.top=0;
    while(t||(s.top=0))
    {
        if(t)
        {
            push(&s,t);//入栈 
            t=t->lchild;//指向左孩子 
        }
        else
        {
            t=pop(&s);//头结点出栈
            printf("%c",t->data);//打印头结点 
            t=t->rchild; //指向右孩子 
        }
    }
}

//后序遍历 
void post(bintree t)
{
    seq s;
    s.top=0;
    while(t||(s.top!=0))
    {
        if(t)
        {
            s.data[s.top]=t;
            s.tag[s.top]=0;
            s.top++;
            t=t->lchild;
        }
        else if(s.tag[s.top-1]==1)
        {
            s.top--;
            t=s.data[s.top];
            printf("%c",t->data);
            t=NULL;
        }
        else
        {
            t=s.data[s.top-1];
            s.tag[s.top-1]=0;
            t=t->rchild;
        }
    }
 } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值