前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PAT(甲级)1138.Postorder Traversal(25)

PAT(甲级)1138.Postorder Traversal(25)

作者头像
lexingsen
发布2022-02-25 08:06:49
2270
发布2022-02-25 08:06:49
举报
文章被收录于专栏:乐行僧的博客

PAT 1138.Postorder Traversal(25) 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. 输入格式: 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.

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

输入样例:

代码语言:javascript
复制
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6

输出样例:

代码语言:javascript
复制
3

题目分析:模板题,根据中序遍历和前序遍历求解后序遍历序列的第一个元素。

注意:应该牢牢掌握以下三种二叉树的重构。 1.前序+中序 2.中序+后序 3.中序+层序

AC代码:

代码语言:javascript
复制
#include <iostream>
using namespace std;

const int maxn = 50010;
int mid[maxn] = {0};
int pre[maxn] = {0};
int post[maxn] = {0};
int n, idx=1;

struct node{
    int data;
    node* lchild;
    node* rchild;
};

node* build(int preL, int preR, int inL, int inR){
    if(preL > preR)return NULL;
    node* root = new node;
    root->data = pre[preL];
    int k;
    for(k = inL; k<=inR; ++k){
        if(mid[k] == pre[preL])
            break;
    }
    int numLeft = k - inL;
    root->lchild = build(preL+1, preL+numLeft, inL, k-1);
    root->rchild = build(preL+numLeft+1, preR, k+1, inR);
    return root;
}

void postorder(node* root){
    if(root){
        postorder(root->lchild);
        postorder(root->rchild);
        post[idx ++] = root->data;
    }
}
int main(){
    scanf("%d", &n);
    for(int i=1; i<=n; ++i){scanf("%d", &pre[i]);}
    for(int i=1; i<=n; ++i){scanf("%d", &mid[i]);}
    node* root = build(1, n, 1, n);
    postorder(root);
    cout<<post[1]<<endl;
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档