这题就是很常规。。。就是后序遍历应该可以再优化一下,应该得到第一个数字就可以return了(post的方法出口换成 if(root==NULL||post.size()>=1)return ;试了一下发现时间还变多了=^= :可能是构造二叉树的时间就比较多吧。。),如果时间允许范围再小一点可能会超时 :所以可以考虑一下优化
我的博客还有一篇是采用静态构造二叉树的方法,就不需要构造二叉树了。作为第二种方法把 https://blog.youkuaiyun.com/Liberalspirit/article/details/107061950
#include<cstdio>
#include<string>
#include<iostream>
#include<vector>
#include <algorithm>//fill()在里面
#include <cmath>
#include<queue>
#include<unordered_set>
#include<set>
#include<map>
#include <cstdlib>//貌似是free,malloc等函数的头文件:含有NULL
using namespace std;
//A1138 后序遍历
//二叉树:权重都大于0 :给出先序和中序遍历,输出该树后序遍历的第一个节点
const int INF=1e9; //fill(map[0],map[0]+maxn*maxn,INF);
const int maxn=10010;
vector<int> pre,inorder;//只存权重即可
struct node{
int weight;
node* left;
node* right;
}root;
//递归生成树
node* buildTree(int preL,int preR,int inL,int inR){
node* root=new node;
//递归出口
if(preL>preR) return NULL;
int head=pre[preL];
//你没有赋值
root->weight=head;
int k=-1;
for(k=inL;k<=inR;k++){
if(inorder[k]==head)break;
}
//k是中序遍历中根节点的位置
int leftNum=k-inL;
root->left=buildTree(preL+1,preL+leftNum,inL,k-1);
root->right=buildTree(preL+leftNum+1,preR,k+1,inR);
return root;
}
vector<int> post;
void getPost(node* root){
//后序遍历->递归
if(root==NULL)return ;
getPost(root->left);
getPost(root->right);
post.push_back(root->weight);
}
int main(){
int n;
cin>>n;
int temp;
//存放先序
for(int i=0;i<n;i++){
cin>>temp;
pre.push_back(temp);
}
//存放中序
for(int i=0;i<n;i++){
cin>>temp;
inorder.push_back(temp);
}
node* Root=buildTree(0,n-1,0,n-1);
// cout<<"root="<<Root->weight<<endl;
getPost(Root);
cout<<post[0]<<endl;
return 0;
}
补充:第二种方法
#include<cstdio>
#include<string>
#include<iostream>
#include<vector>
#include <algorithm>//fill()在里面
#include <cmath>
#include<queue>
#include<unordered_set>
#include<set>
#include<map>
#include <cstdlib>//貌似是free,malloc等函数的头文件:含有NULL
using namespace std;
//A1138 后序遍历
//二叉树:权重都大于0 :给出先序和中序遍历,输出该树后序遍历的第一个节点
const int INF=1e9; //fill(map[0],map[0]+maxn*maxn,INF);
const int maxn=10010;
vector<int> pre,inorder,post;//只存权重即可
void preInToPost(int root,int start,int end){
if(start>end || post.size()>=1)return;
int data=pre[root];//根节点
int k;
for(k=start;k<=end;k++){
if(inorder[k]==data)break;
}
int leftNum=k-start;
preInToPost(root+1,start,k-1);
preInToPost(root+leftNum+1,k+1,end);//右子树的根节点
//后序在这里记录
post.push_back(data);//根节点数据
}
int main(){
int n;
cin>>n;
int temp;
//存放先序
for(int i=0;i<n;i++){
cin>>temp;
pre.push_back(temp);
}
//存放中序
for(int i=0;i<n;i++){
cin>>temp;
inorder.push_back(temp);
}
preInToPost(0,0,n-1);
cout<<post[0]<<endl;
return 0;
}