【问题描述】
树和二叉树基本上都有先序、中序、后序、按层遍历等遍历顺序,给定中序和其它一种遍历的序列就可以确定一棵二叉树的结构。
假定一棵二叉树一个结点用一个字符描述,现在给出中序和按层遍历的字符串,求该树的先序遍历字符串。
【输入格式】
两行,每行是由大写字母组成的字符串(一行的每个字符都是唯一的),分别表示二叉树的中序遍历和按层遍历的序列。
【输出格式】
一行,表示二叉树的先序序列。
【数据范围】
输入字符串的长度均不超过26。
【输入样例】
DBEAC
ABCDE
【输出样例】
ABDEC
【算法代码】
#include <bits/stdc++.h>
using namespace std;
string InOrder, LevelOrder;
void getPreOder(int b1,int e1,int b2,int e2) {
int i,j;
for(i=b2; i<=e2; i++) {
int flag=0;
for(j=b1; j<=e1; j++) {
if(LevelOrder[i]==InOrder[j]) {
cout<<LevelOrder[i];
flag=1;
break;
}
}
if(flag) break;
}
if(j>b1) getPreOder(b1,j-1,0,e2);
if(j<e1) getPreOder(j+1,e1,0,e2);
}
int main() {
cin>>InOrder>>LevelOrder;
getPreOder(0,InOrder.length()-1,0,LevelOrder.length()-1);
return 0;
}
/*
in:
DBEAC
ABCDE
out:
ABDEC
*/
【参考文献】
https://blog.csdn.net/weixin_42720231/article/details/116711712
https://www.acwing.com/solution/content/32566/