#include <bits/stdc++.h>
#define endl '\n'
#define INF 0x3f3f3f3f
#define ll long long
#define pb push_back
#define int long long
#define Mirai ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
using namespace std;
typedef pair<int, int> pii;
const int N = 1100;
struct tree
{
char dat;
int l,r;
}tr[N];
int now,tot;//now代表当前pre中根节点找到了那个位置
//由于先序遍历对于每一棵子树都一定是先遍历根节点,再分别遍历左右子树
//所以我们只需要在中序遍历中找到根节点的位置
//在根节点左边的就是左子树,右边的就是右子树
string pre,mid;//分别代表先序遍历和中序遍历
int rebuild(int l,int r)
{
if(l>r)return 0;//0就代表没有此节点
int m;
for(int i=l;i<=r;i++)//在中序遍历中寻找根节点
{
if(mid[i]==pre[now])
{
m=i;//记录根节点在中序遍历中的位置
break;
}
}
tr[++tot].dat=pre[now++];//将根节点存入二叉树中
int root=tot;//记录当前节点位置
tr[root].l=rebuild(l,m-1);//建立左子树
tr[root].r=rebuild(m+1,r);//建立右子树
return root;//返回根节点位置
}
void finprint(int root)
{
if(root)
{
finprint(tr[root].l);
finprint(tr[root].r);
cout<<tr[root].dat;
}
}
void floorprint(int root)
{
queue<int> q;
if(root)q.push(root);
while(q.size())
{
auto t=q.front();
q.pop();
cout<<tr[t].dat;
if(tr[t].l)q.push(tr[t].l);
if(tr[t].r)q.push(tr[t].r);
}
}
void solve()
{
cin>>pre>>mid;
now=0;
int root=rebuild(0,pre.size()-1);
finprint(root);
cout<<endl;
floorprint(root);
cout<<endl;
}
signed main()
{
Mirai;
int T = 1;
cin>>T;
while (T--)
{
solve();
}
return 0;
}
F - 数据结构实验之求二叉树后序遍历和层次遍历
于 2023-01-29 23:23:37 首次发布