[sicily]1935. 二叉树重建

来源:互联网 发布:top k 算法 编辑:程序博客网 时间:2024/05/19 13:07

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 0
原创粉丝点击