题目
假设二叉树上各结点的权值互不相同且都为正整数。
给定二叉树的后序遍历和中序遍历,请你输出二叉树的前序遍历的最后一个数字。
数据范围
1≤N≤500001≤N≤50000,
二叉树结点权值范围 [1,1e9]。
思路
跟之前做的题不一样,数据范围大,开结点数组存储树节点会导致错误。所以利用map把中序遍历的下标存下来就好了,其他的还是与之前写过的类似。
代码
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
const int N = 50010;
//const int M = 1e9 + 10;
typedef long long ll;
int n;
vector<int> postOrder;
vector<int> inOrder;
unordered_map<int,int> m;
long long ans = 0;
// struct node{
// int left;
// int right;
// }nodes[M];
void build(int inL,int inR,int postL,int postR)
{
if(postL > postR) return;
int root = postOrder[postR];
//获得中序遍历中根节点的下标
int index = m[root];
ans = root;
//index-inL表示左节点数量
build(inL,index - 1,postL,postL + index - inL - 1);
build(index + 1,inR,postL &#