树的遍历(根据后序和中序建树并输出层次遍历序列)

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

输入格式:

输入第一行给出一个正整数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

作者: 陈越

单位: 浙江大学

时间限制: 400 ms

内存限制: 64 MB

 完整代码:

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=50;
struct node
{
    int data,l,r;
}tree[maxn];
int last[maxn],mid[maxn],cnt;

int build(int last[],int mid[],int n)
{
    int root=last[n];//每次从后序序列中拿出最后一个元素作为根结点
    if(n<=0){
        return -1;
    }
    if(n==1){
        tree[++cnt].data=mid[1];
        tree[cnt].l=tree[cnt].r=-1;
        return cnt;
    }
    tree[++cnt].data=root;
    int next=cnt;
    int pos;
    for(pos=1;pos<=n;pos++){//每次在中序序列中找当前在后序中拿出来的根结点对应的在中序中的位置
        if(mid[pos]==root) break;
    }
    tree[next].l=build(last,mid,pos-1);//递归找左子树
    tree[next].r=build(last+pos-1,mid+pos,n-pos);//递归找右子树,注:找右子树是对应的子树的序列为当前的右半段,即last+pos-1和mid+pos,数组名+一个数x,代表原数组的x位置~最后的那部分
    return next;
}

void output()
{
    queue<int>q;
    q.push(1);
    while(!q.empty()){
        int node=q.front();
        q.pop();
        if(node!=1){
            cout<<" ";
        }
        cout<<tree[node].data;
        if(tree[node].l!=-1){
            q.push(tree[node].l);
        }
        if(tree[node].r!=-1){
            q.push(tree[node].r);
        }
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>last[i];
    }
    for(int i=1;i<=n;i++){
        cin>>mid[i];
    }
    build(last,mid,n);
    output();
    return 0;
}
发布了89 篇原创文章 · 获赞 5 · 访问量 6698

猜你喜欢

转载自blog.csdn.net/Mr_Kingk/article/details/104041229