[sicily]1935. 二叉树重建

1935. 二叉树重建

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

对于二叉树T,可以递归定义它的先序遍历、中序遍历和后序遍历如下: PreOrder(T)=T的根节点+PreOrder(T的左子树)+PreOrder(T的右子树) InOrder(T)=InOrder(T的左子树)+T的根节点+InOrder(T的右子树) PostOrder(T)=PostOrder(T的左子树)+PostOrder(T的右子树)+T的根节点 其中加号表示字符串连接运算。例如,对下图所示的二叉树,先序遍历为DBACEGF,中序遍历为ABCDEFG。 
输入一棵二叉树的先序遍历序列和中序遍历序列,输出它的广度优先遍历序列。 

Input

第一行为一个整数t(0<t<10),表示测试用例个数。 以下t行,每行输入一个测试用例,包含两个字符序列s1和s2,其中s1为一棵二叉树的先序遍历序列,s2为中序遍历序列。s1和s2之间用一个空格分隔。序列只包含大写字母,并且每个字母最多只会出现一次。 

Output

为每个测试用例单独一行输出广度优先遍历序列。 

Sample Input

2 
DBACEGF ABCDEFG 
BCAD CBAD 

Sample Output

DBEACGF 
BCAD

树的数据结构题,根据前序遍历、中序遍历序列,重新构建出原来的二叉树结构,然后进行广度优先遍历输出遍历序列。具体代码如下:


#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
using namespace std; 

string s1,s2;
int pos;

struct Node
{
    char ch;
    struct Node *left;
    struct Node *right; 
};
//广度优先输出遍历序列
void bfs(struct Node *&root)
{
    queue<struct Node*> q;
    q.push(root);
    while(!q.empty())
    {
        Node *current = q.front();
        q.pop();
        cout<<current->ch;
        if(current->left != NULL)q.push(current->left);
        if(current->right != NULL)q.push(current->right); 
    }
}
//递归重建二叉树结构
void ReconstructBTree(Node *&root, int begin, int end)
{
    if(pos >= s1.size() || begin>end)
        return ;
    root = new Node();
    root->ch = s1[pos];
    root->left = NULL;
    root->right = NULL;
    int mid = s2.find(s1[pos++]);
    ReconstructBTree(root->left,begin,mid-1);
    ReconstructBTree(root->right,mid+1,end);
}

int main()
{
    int t; 
    cin>>t;
    while(t--)
    {
        cin>>s1>>s2;
        pos = 0;
        struct Node *root=NULL;
        int len = s1.size();
        ReconstructBTree(root,0,len);
        bfs(root);
        cout<<endl;
    }
    //system("pause");
    return 0;   
}                                 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值