L2-006. 树的遍历(不建树)

L2-006. 树的遍历

 

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

输入格式:

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

思路:偷个懒不创建二叉树的,直接递归知道每个数是第几层然后存放在优先队列中,但是没有AC,然后我想了一下好像一层中的键值出现的顺序可能不一样,开始觉得这种方法是错误的,但是后面想了一下,根据中序能知道同一层元素中输出的优先顺序,于是加入了在结构体中quan,这个就是最后一个测试点。
#include<set>
#include<map>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
struct Node{
    int key;
    int quan;
    int ceng;
    bool operator < (const Node &a)const
    {
        if (a.ceng!=ceng)
        return a.ceng < ceng;
        else return a.quan < quan;
    }
};
int n; 
int b[40];
map<int, int>ma;
priority_queue<Node>que;
void Print(int s,int e,int c)
{
    if (s>e)return;
    Node node;
    if (s == e){
        node.ceng = c;
        node.quan = s;
        node.key = b[s];
        que.push(node);
    }
    else{
        int max = ma[b[s]], ss = s;
        for (int i = s; i <= e; i++)
        if (ma[b[i]] > max){
            max = ma[b[i]];
            ss = i;
        }

        node.ceng = c;
        node.quan = ss;
        node.key = b[ss];
        que.push(node);

        Print(s, ss - 1, c + 1);
        Print(ss + 1, e, c + 1);
    }
    
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++){
        int num; cin >> num;
        ma.insert(pair<int, int>(num, i));
    }
    for (int i = 0; i < n; i++)
        cin >> b[i];

    Print(0, n - 1, 0);
    for (int i = 1; i <= n; i++){
        if (i == 1)cout << que.top().key;
        else cout << " " << que.top().key;
        que.pop();
    }
    cout << endl;
    return 0;
}


 
原文地址:https://www.cnblogs.com/zengguoqiang/p/8652361.html