题目描述:
输入一棵二叉树的先序遍历序列和中序遍历序列,输出它的广度优先遍历序列。
输入格式:
第一行为一个整数t(0<t<10),表示测试用例个数。 以下t行,每行输入一个测试用例,包含两个字符序列s1和s2,其中s1为一棵二叉树的先序遍历序列,s2为中序遍历序列。s1和s2之间用一个空格分隔。序列只包含大写字母,并且每个字母最多只会出现一次。
输出格式:
为每个测试用例单独一行输出广度优先遍历序列。
样例输入:
2
DBACEGF ABCDEFG
BCAD CBAD
样例输出:
DBEACGF
BCAD
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
char s1[1001], s2[1001];
int l[1001], r[1001];
void build_tree(int first, int last, int d){
if(first >= last) return;
int i;
for(i = first; i <= last+d; i++) if(s1[first] == s2[i-d]) break;
if(i>first) {
l[first] = first+1;
build_tree(first+1, i, d+1);
}
if(i<last){
r[first] = i+1;
build_tree(i+1, last, d);
}
}
int main(){
int T;
cin >> T;
while(T--){
memset(l, -1, sizeof(l));
memset(r, -1, sizeof(r));
cin >> s1 >> s2;
int len = strlen(s1);
build_tree(0, len-1, 0);
queue<int> q;
q.push(0);
while(!q.empty()){
if(l[q.front()] != -1) q.push(l[q.front()]);
if(r[q.front()] != -1) q.push(r[q.front()]);
cout << s1[q.front()];
q.pop();
}
if(T) cout << endl;
}
return 0;
}