F - 数据结构实验之求二叉树后序遍历和层次遍历

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值