数据结构实验之求二叉树后序遍历和层次遍历

9 篇文章 0 订阅
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct tnode
{
    char data;
    tnode *lc,*rc;
}*tree;

void build(tree &t,char *he,char *mid,int len)  //数组用字符来代替
{
    if(len==0) t=NULL;  //递归停止条件
    else
    {
        int k=0;
        int n=strlen(mid);
        for(;k<n;k++)      //寻找根节点
        {
            if(mid[k]==*he)
                break;
        }
        t=new(tnode);
        t->data=*he;

        build(t->lc,he+1,mid,k);     //t->lc;  递归左子树

        build(t->rc,he+k+1,mid+k+1,len-(k+1));   //t->rc;  递归右子树
    }
}

void last(tree &t)  //后序遍历
{
    if(t)
    {
        last(t->lc);
        last(t->rc);
        printf("%c",t->data);
    }
}

typedef struct qnode   //队节点
{
    tree data;
    qnode *next;
}*qtype;
typedef struct        //队的定义
{
    qtype front,rear;
}que;

void QueInitial(que &q)   //队的初始化
{
    q.front=q.rear=new(qnode);
    q.front->next=NULL;
}

void InQue(que &q,tree &e)     //队的插入
{
    qtype p;
    p=new(qnode);
    p->data=e;
    p->next=NULL;
    q.rear->next=p;
    q.rear=p;
}

char DelQue(que &q,tree &e)
{
    qtype p;
    if(q.front==q.rear) return 0;
    p=q.front->next;
    e=p->data;
    q.front->next=p->next;
    if(q.rear==p)
        q.rear=q.front;
    free(p);
}

char QueEmpty(que &q)
{
    if(q.front==q.rear) return 1;
    else return 0;
}

void ceng(tree &t)
{
    que q;
    QueInitial(q);
    if(t)
        InQue(q,t);
    while(!QueEmpty(q))
    {
        DelQue(q,t);
        printf("%c",t->data);
        if(t->lc)
            InQue(q,t->lc);
        if(t->rc)
            InQue(q,t->rc);
    }
}

int main()
{
    int n;
    char he[55],mid[55];
    tree t;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s %s",he,mid);
        int len=strlen(he);
        build(t,he,mid,len);
        last(t);
        printf("\n");
        ceng(t);
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值