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

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1138 Postorder Traversal (pintia.cn)
🔑中文翻译:后序遍历
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

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

Sample Output:

3
题意

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

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LqT48KDi-1664681878318)(PAT 甲级辅导.assets/4.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;
}
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值