uicccui 2021-11-17 20:03 采纳率: 42.9%
浏览 43
已结题

postorder后序遍历(需要完整代码)

题目描述

Given the pre-order traversal sequence A[] and in-order traversal sequence B[] of a tree, find the post-order traversal sequence.
输入描述

Input contains 3 lines;
The first line contains an integer n(n <= 100000), the number of node in the tree.
The second line contains n distinct intergers, which is the sequence A[](0 <= a0,a2,…,an-1<= n-1).
The third line contains n distinct intergers, which is the sequence B[](0 <= b0,b2,…,bn-1<= n-1).
输出描述

The postorder traversal sequence of the tree.
输入样例

10
7 2 0 5 8 4 9 6 3 1
7 5 8 0 4 2 6 3 9 1
输出样例

8 5 4 0 3 6 1 9 2 7

  • 写回答

1条回答 默认 最新

  • 南七灵 2021-11-17 20:17
    关注
    
    
    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int pos, n;
    
    vector<int> pre, in, post;
    
    void rec(int l, int r)
    {
        if (l >= r)
            return;
        int root = pre[pos++];
        int mid = distance(in.begin(), find(in.begin(), in.end(), root));
        rec(l, mid);
        rec(mid + 1, r);
        post.push_back(root);
    }
    
    void solve()
    {
        pos = 0;
        rec(0, pre.size());
        for (int i = 0; i < post.size(); i++)
        {
            if (i)
                cout << " ";
            cout << post[i];
        }
        cout << endl;
    }
    
    int main()
    {
        while (cin >> n)
        {
            pre.clear();
            in.clear();
            post.clear();
    
            for (int i = 0; i < n; i++)
            {
                int k;
                cin >> k;
                pre.push_back(k);
            }
    
            for (int i = 0; i < n; i++)
            {
                int k;
                cin >> k;
                in.push_back(k);
            }
    
            solve();
        }
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月26日
  • 已采纳回答 11月18日
  • 创建了问题 11月17日

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题