sdut oj 求二叉树的层次遍历(先序中序->二叉树 层序输出)(数组模拟)

链表题解链接见下
sdut oj 求二叉树的层次遍历(先序中序->二叉树 层序输出)(链表).
数组模拟见下文

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

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

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

Sample
Input

2
abc
bac
abdec
dbeac

Output

abc
abcde

C++

/*
time : 2021年7月26日17:22:29
result : accept
author : kirie
tips : null
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define rep(i,a,n) for(int i=a;i<n;i++)
using namespace std;
const int N=1e4+7;

struct tree {
    char data;///字符型数据
    int lc, rc;///左孩子,右孩子
}a[N];///节点的结构

int cnt;///树的序号,当有元素要存到里面时才自增1

int create(char pre[], char mid[], int len){
    if(len <= 0)
        return -1;
    int id = cnt ++;
    a[id].data = pre[0];
    int i;
    for(i = 0;i < len; i++){
        if(mid[i] == pre[0])
            break;
    }
    a[id].lc = create(pre+1, mid, i);
    a[id].rc = create(pre+1+i, mid+1+i, len-i-1);
    return id;
}

void seq_show(int root){//Sequence 层序
    if(root == -1) return ;
    queue<int> q;
    q.push(root);
    while(!q.empty()){
        int id = q.front();
        q.pop();
        printf("%c",a[id].data);
        if(a[id].lc != -1)
            q.push(a[id].lc);
        if(a[id].rc != -1)
            q.push(a[id].rc);
    }
}

int main()
{
    int t;
    cin>>t;
    while(t--){
        char str1[N],str2[N];//先序,中序
        cin>>str1>>str2;
        int root = create(str1, str2, strlen(str1));//先序,中序,长度
        seq_show(root);
        cout<<endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值