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



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

输入

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

输出

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

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu

示例输出

dgebfca
abcdefg
linux
xnuli


Memory: 272 KB Time: 0 MS
Language: g++ Result: Accept
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

char a[1000],b[1000];
struct node

{
    char data;
    struct node *l,*r;
};
struct node *build(char *a,char *b,int n)
{
    if(n<=0)
    {
        return NULL;
    }
    char x = a[0];///找到根节点
    struct node *t;
    t = (struct node *)malloc(sizeof(struct node ));
    t->data = x;
    int i;
    for(i=0;i<n;i++)
    {
        if(b[i] == x)///排除重复遍历
            break;
    }
    t->l = build(a+1,b,i);///右子树+1
    t->r = build(a+i+1,b+i+1,n-i-1);
    return t;
}

void last(struct node *t)///后序遍历
{
    if(t!=NULL)
    {
        last(t->l);
        last(t->r);
        printf("%c",t->data);
    }
}

void add(struct node *t)///层次遍历
{
    struct node *f[1000];
    int in=1,out=0;
    f[0] = t;
    while(in>out)///队列不为空
    {
        if(f[out])//一次遍利一层 将一层的所有子树加进队列
        {
            printf("%c",f[out]->data);
            f[in] = f[out]->l;//左孩子进列
            in++;
            f[in] = f[out]->r;//有孩子进列
            in++;
            out++;
        }
        else
            out++;

    }
}  

/*void cengci(struct node *r)  

{  

   struct node *p;  

    struct node *qu[N];//定义环形队列,存放结点指针  

    int head,wei;//定义队头,队尾指针  

    headwei =-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;  

        }  

    }

}*/

int main()

{ int m;

struct node *tree;

while(~scanf("%d",&m))

{

while(m--)

{

scanf("%s%s",a,b);

int len = strlen (a);

tree = build(a,b,len);

last(tree);

printf("\n");

add(tree);

printf("\n");

}

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值