首页 > 其他 > 详细

L2-011 玩转二叉树 (25 分)

时间:2021-04-20 00:27:32      阅读:19      评论:0      收藏:0      [点我收藏+]

题目大意

给一个二叉树的中序遍历和前序遍历,求其镜像后的层序遍历
类似于 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;
}

L2-011 玩转二叉树 (25 分)

原文:https://www.cnblogs.com/alexdzk/p/14678324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!