侧边栏
首页代码

L2-011 玩转二叉树 (25 分)(已知前序 中序)

题目大意

给一个二叉树的中序遍历和前序遍历,求其镜像后的层序遍历
类似于 L2-006 树的遍历 (25 分)

建树 镜像就在dfs的时候先输出右子树 再 左子树

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int l,r;
}tree[35];
int pre[35],in[35];
vector<int> ans;
int create(int l1,int r1,int l2,int r2)//1-中 2-前
{
    if(l1>r1||l2>r2)
        return 0;
    int p=l1;
    while(in[p]!=pre[l2]) p++;
    int cnt = p-l1;
    int rt = pre[l2];
    tree[rt].l=create(l1,p-1,l2+1,l2+cnt);
    tree[rt].r=create(p+1,r1,l2+cnt+1,r2);
    return rt;
}
void dfs(int rt)
{
    queue<int> q;
    q.push(rt);
    ans.push_back(rt);
    while(!q.empty())
    {
        int t=q.front();
        q.pop();
        if(tree[t].r!=0)
        {
            q.push(tree[t].r);
            ans.push_back(tree[t].r);
        }
        if(tree[t].l!=0)
        {
            q.push(tree[t].l);
            ans.push_back(tree[t].l);
        }
    }
}
int main()
{
    int n;
    cin>>n;
    for(int i =0;i<n;i++)
    {
        cin>>in[i];
    }
    for(int i=0;i<n;i++)
    {
        cin>>pre[i];
    }
    create(0,n-1,0,n-1);
    dfs(pre[0]);
    int f= 1;
    for(auto it:ans)
    {
        if(f)
        {
            f=0;
            cout<<it;
        }
        else
        {
            cout<<" "<<it;
        }
    }
    cout<<endl;
}
posted @ 2021-04-19 19:26  AlexStraightUp  阅读(69)  评论(0)    收藏  举报
页脚HTML代码