sdut oj 求二叉树的层次遍历(先序中序->二叉树 层序输出)(链表)

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

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

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

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

Sample
Input

2
abc
bac
abdec
dbeac

Output

abc
abcde

C++

/*
time : 2021年6月23日23:42:29
result : accept
author : kirie
tips : null
*/
#include <iostream>
#include <cstring>
#include <queue>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N = 107;
typedef struct TreeNode{
    char val;
    struct TreeNode* LChild;
    struct TreeNode* RChild;
}Node;

Node* CreateTree(char pre[], char mid[], int len){
    if(len <= 0)
        return NULL;
    Node *root = new Node;
    root->val = pre[0];
    int i;
    for(i = 0;i < len; i++){
        if(mid[i] == pre[0])
            break;
    }
    root->LChild = CreateTree(pre+1, mid, i);
    root->RChild = CreateTree(pre+1+i, mid+1+i, len-i-1);
    return root;
}

void lev_show(Node* root){
    queue<Node*>que;
    Node* t;
    if(!root)
        return ;
    que.push(root);
    while(!que.empty()){
        t = que.front();
        que.pop();
        cout<<t->val;
        if(t->LChild)
            que.push(t->LChild);
        if(t->RChild)
            que.push(t->RChild);
    }
}

int main()
{
    int t;
    cin>>t;
    while(t--){
        char str1[N],str2[N];
        cin>>str1>>str2;
        Node* root = new Node;
        root = CreateTree(str1, str2, strlen(str1));
        lev_show(root);
        cout<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值