PAT甲级1138 Postorder Traversal (25分)|C++实现

一、题目描述

原题链接
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

二、解题思路

二叉树中序前序转后序,可以用递归的方法还原整棵树。牢牢把握住二叉树的前序遍历的第一个结点即为根结点这个特点,随后在中序遍历序列中找到对应的结点,即可分开左右子树,然后对左右子树分别递归处理即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<unordered_map>
using namespace std;
const int maxn = 50010;
int pre[maxn], in[maxn];
unordered_map<int, int> pos;    //标记每个结点在中序遍历序列中的位置
bool flag = false;
struct Node
{
    
    
    int key, lchild = -1, rchild = -1;
}node[maxn];
int findRoot(int inL, int inR, int preL, int preR)
{
    
    
    if(preL > preR) return -1;  //递归边界
    int root = pos[pre[preL]];  //根结点即为先序遍历序列的第一个点
    node[root].lchild = findRoot(inL, root-1, preL+1, preL+root-inL);   //递归查找左子树根结点
    node[root].rchild = findRoot(root+1, inR, preL+root-inL+1, preR);   //递归查找右子树根结点
    return root;
}
void printLeft(int root)    //与后序遍历类似
{
    
    
    if(flag == false && node[root].lchild != -1) printLeft(node[root].lchild);  //先递归左子树
    if(flag == false && node[root].rchild != -1) printLeft(node[root].rchild);
    if(!flag)   //第一个叶子结点即后序遍历第一个访问的叶子结点,访问过后flag设为true,退出递归
    {
    
    
        printf("%d", node[root].key);
        flag = true;
    }
    return;
}
int main()
{
    
    
    int N;
    scanf("%d", &N);
    for(int i=1; i<=N; i++) scanf("%d", &pre[i]);
    for(int i=1; i<=N; i++)
    {
    
    
        scanf("%d", &in[i]);
        pos[in[i]] = i;
        node[i].key = in[i];
    }
    int root = findRoot(1, N, 1, N);
    printLeft(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109048530
今日推荐