二叉树遍历C++

假设二叉树上各结点的权值互不相同且都为正整数。
给定二叉树的后序遍历和中序遍历,请你输出二叉树的前序遍历的最后一个数字。

输入格式
第一行包含整数 N,表示二叉树结点总数。
第二行给出二叉树的后序遍历序列。
第三行给出二叉树的中序遍历序列。

输出格式
输出二叉树的前序遍历的最后一个数字。

数据范围
1≤N≤50000,
二叉树结点权值范围 [1,109]。

输入样例:
7
1 2 3 4 5 6 7
2 1 4 3 7 5 6

输出样例:
5

#include<iostream>
#include<unordered_map>
using namespace std;
const int N=50010;
int a[N],b[N],res,n;
unordered_map<int,int> p;
void build(int al,int ar,int bl,int br)
{
   
    if(al>ar) return;
    int root=a[ar];
    int k=p[root];
    res=root;
    build(al,al+k-bl-1,bl,k-1);
    build(al+k-bl,ar-1,k+1,br);
}
int main()
{
   
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    for(int i=0;i<n;i++){
   
        cin>>b[i];
        p[b[i]]=i;
    }
    build(0,n-1,0,n-1);
    cout<<res;
    return 0;
}

相关推荐

  1. C++

    2024-01-16 20:58:05       62 阅读
  2. C语言

    2024-01-16 20:58:05       46 阅读
  3. 算法笔记—

    2024-01-16 20:58:05       51 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-16 20:58:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-16 20:58:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-16 20:58:05       82 阅读
  4. Python语言-面向对象

    2024-01-16 20:58:05       91 阅读

热门阅读

  1. Vue2:利用watch和localStorage存储数据案例

    2024-01-16 20:58:05       58 阅读
  2. JPA查询PostgreSQL行排序问题

    2024-01-16 20:58:05       50 阅读
  3. Socket-Worker模式

    2024-01-16 20:58:05       63 阅读
  4. Snakemake:初探

    2024-01-16 20:58:05       55 阅读
  5. 融优学堂-艺术史

    2024-01-16 20:58:05       38 阅读
  6. computed和watch和watchEffect 相同和不同

    2024-01-16 20:58:05       59 阅读
  7. 【速成】蓝桥杯嵌入式省一教程

    2024-01-16 20:58:05       59 阅读