【PAT甲级 - C++题解】1138 Postorder Traversal

简介: 【PAT甲级 - C++题解】1138 Postorder Traversal

1138 Postorder Traversal


Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:


For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.


Sample Input:

7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
• 1
• 2
• 3

Sample Output:

3


题意


给定前序遍历和中序遍历的结果,构建二叉树。

要求输出该二叉树的后序遍历结果的第一个元素值。


思路


  1. 由于题目给定每个结点的值都不同,所以可以用哈希表存储每个结点在中序数组中的下标,方便后续使用。
  2. 通过下标构建二叉树(其中 k-il-1 表示左子树结点个数):



e7a37d75c98b4305a913d0fdebf59adf.png



  1. 因为构建二叉树的时候是先去递归左子树,所以第一个遍历到的结点就是二叉树最左边的那个点,而后序遍历结果的第一个点就是二叉树最左边的那个点,故只用在构建过程中记录一下即可。

代码

#include<bits/stdc++.h>
using namespace std;
const int N=50010;
int n;
int pre[N],in[N];
unordered_map<int,int> pos;
int post;
void build(int il,int ir,int pl,int pr)
{
    int root=pre[pl];
    int k=pos[root];
    if(il<k)    build(il,k-1,pl+1,pl+1+k-il-1);
    if(ir>k)    build(k+1,ir,pl+1+k-il-1+1,pr);
    if(!post)   post=root;
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)    cin>>pre[i];    //输入前序数组
    for(int i=0;i<n;i++)    //输入中序数组,并记录每个元素的下标
    {
        cin>>in[i];
        pos[in[i]]=i;
    }
    build(0,n-1,0,n-1);
    cout<<post<<endl;
    return 0;
}


目录
相关文章
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
303 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
382 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
363 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
331 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
257 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
304 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
511 0
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
758 12
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)