【天梯赛】L2-006. 树的遍历(输出二叉树的层序遍历)

25 篇文章 0 订阅
3 篇文章 0 订阅

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

思路:
通过给出的后序遍历,确定二叉树的根,然后在中序遍历中找到根的位置,它的左右两边就是它的左右子树,对根节点进一步递归,先重建右子树,找到这棵子树的根节点也就是根的右子节点,一直递归下去,左子树类似。
参考:https://blog.csdn.net/Hacker_ZhiDian/article/details/60776494

#include <bits/stdc++.h>
using namespace std;

#define mem(a,n) memset(a,n,sizeof(a))
#define memc(a,b) memcpy(a,b,sizeof(b))
#define rep(i,a,n) for(int i=a;i<n;i++) ///[a,n)
#define pb push_back
#define IO ios::sync_with_stdio(false)
#define fre freopen("in.txt","r",stdin)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
const double PI=acos(-1.0);
const double E=2.718281828459045;
const double eps=1e-7;
const int INF=0x3f3f3f3f;
const int MOD=1e8+7;
const int N=1e4+5;
const ll maxn=1e6+5;
const int dir[4][2]= {-1,0,1,0,0,-1,0,1};
const ll inf=0x3f3f3f3f3f3f3f3f;

int num;
int in[N],pos[N];
struct Node
{
    int l,r,w;
}tree[N];
void build(int l,int r,int n)///n表示树的节点的下标
{
    if(l>=r)
    {
        tree[n].w=INF;
        return ;
    }
    int root=pos[num--];
    tree[n].l=n<<1;
    tree[n].r=n<<1|1;
    tree[n].w=root;
    ///通过find()找到根root在 先序遍历中的位置递归建树
    int pp=find(in,in+r,root)-in;
    build(pp+1,r,n<<1|1);///建立右子树
    build(l,pp,n<<1);///建立左子树
}
void input(int *a,int n)
{
    rep(i,0,n) cin>>a[i];
}
void output()
{
    queue<int>que;
    que.push(1);///这里添加1  是因为构造二叉树时下标是从1开始的
    while(!que.empty())
    {
        int now=que.front();
        //printf("now=%d\n",now);
        que.pop();
        if(tree[now].w!=INF)
        {
            if(now!=1) cout<<" ";
            cout<<tree[now].w;
            que.push(tree[now].l);
            que.push(tree[now].r);
        }
    }
    cout<<endl;
}
int main()
{
    int n;
    cin>>n;
    num=n-1;
    input(pos,n);
    input(in,n);
    build(0,n,1);
    output();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值