二叉树后序遍历和层次遍历

 

已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

输入

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

输出

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu

示例输出

dgebfca
abcdefg
linux
xnuli

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 1000
   struct node
{
 char data;
 struct node *left;
    struct node *right;
};struct node  *make(char *a,char *b,int n){
 struct node *now;
 char *p;
 int k = 0;
 if(n<=0)
    {
        return NULL;
    }
 now=(struct node*)malloc(sizeof(struct node));
 (*now).data=*a;
 for(p=b;p<b+n;p++)
    {
        if(*p==*a)
            break;
    }
    k = p - b;
 (*now).left=make(a+1,b,k);
 (*now).right=make(a+1+k,p+1,n-k-1);
 return now;
}
void cengci(struct node *r)
{
    int i=0,j=1;
    struct node *t[103];
    t[0]=r;
    while(i < j)//队列不为空时
 {
        if(t[i]!=NULL)// i 结点不为空时
  {
            printf("%c",t[i]->data);//访问该节点
            t[j++]=t[i]->left; //左分支进队列
            t[j++]=t[i++]->right; //右分支进队列
        }
        else
            i++;
    }
}
/*void cengci(struct node *r)
{
    struct node *p;
    struct node *qu[N];//定义环形队列,存放结点指针
    int head,wei;//定义队头,队尾指针
    head= wei =-1;//队列初始化为空
    wei ++;
    qu[wei ]=r;//根节点指针进入队列
    while(head != wei )//队列不为空时
    {
        head = (head+1)%N;
        p=qu[head]; //队头元素出列
        printf("%c",p->data);//访问结点        if(p->left != NULL)
        {
            wei = (wei + 1) % N; //有左孩子时将其进队
            qu[wei] = p->left;
        }        if(p->right!=NULL)
        {
            wei=(wei + 1)%N;//有右孩子时将其进队
            qu[wei]=p->right;
        }
    }}*/void lastord(struct node *t){
 if(t==NULL)
        return ;
lastord(t->left);
lastord(t->right);
printf("%c",t->data);
}int main()
{
    int T;
     struct node  *tree;
    char a[100],b[100];
    while(~scanf("%d",&T))
    {
        while(T--)
        {
 scanf("%s",a);
 scanf("%s",b);
 int n=strlen(a);
 tree=make(a,b,n);
 lastord(tree);
 printf("\n");
 cengci(tree); printf("\n");
     }
    }
 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值