2824求二叉树的层次遍历

求二叉树的层次遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。

Input

输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。

Output

每组输出这颗二叉树的层次遍历。

Sample Input

2
abc
bac
abdec
dbeac

Sample Output

abc
abcde

Hint

Source

fmh


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
    char date;
    struct node *left;
    struct node *right;
}tree;
tree *root,*link[54];
char str1[54],str2[54];
tree *get_build(int len,char *str1,char *str2)//建立二叉树
{
    if(len==0)
        return NULL;
    int i;
    tree *root;
    root = (tree *)malloc(sizeof(tree));
    root->date=str1[0];//寻找根节点,新的根节点为前序遍str1的第一个
    for(i=0;i<len;i++)//寻找新的根节点在中序遍历str2中的位置
    {
        if(str2[i]==root->date)
            break;
    }
    root->left = get_build(i,str1+1,str2);//左子树的长度,左子树在前序遍历中的开始位置,左子树在中序遍历中的开始位置
    root->right = get_build(len-i-1,str1+i+1,str2+i+1);//右子树的长度,右子树在前序遍历中的位置,右子树在中序遍历的位置
    return root;
}
void ans(tree *root)//二叉树的层序遍历
{
    if(root)//判断root是否为NULL
    {
        int i=0,j=0;
        link[j++]=root;
        while(i<j)
        {
            if(link[i])
            {
                link[j++]=link[i]->left;//入队
                link[j++]=link[i]->right;//入队
                printf("%c",link[i]->date);//层序遍历
            }
            i++;//出队
        }
    }
}
int main()
{
    int t,len;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s %s",str1,str2);
        len=strlen(str1);
        root = get_build(len,str1,str2);//调用建立二叉树函数
        ans(root);//调用二叉树的层序遍历函数
        printf("\n");

    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值