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.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=50000), 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
由前序,中序找后序,固定的套路,自己递归几次就能明白;
这一题尝试了三次才全部通过测试;主要是内存超存的问题;
因为只需要输出后序遍历的第一个值,第一次提交的时候,做了很多不需要的遍历;
第二次提交的时候,因为dfs是得参数是按值传递的,每次递归都要,复制一次pre和in,会占用大量内存,解决方法是引用调用,则不需要每次复制pre和in,也可以把pre和in申明为全局变量
#include<iostream>
#include<vector>
using namespace std;
bool flag=true;
vector<int> ans;
void dfs(vector<int> pre, vector<int> in, int prel, int inl, int inr){
  int i=inl;
  if(inl>inr) return;
  while(in[i]!=pre[prel]&&i<inr) i++;
  dfs(pre, in, prel+1, inl, i-1);
  dfs(pre, in, prel+1+i-inl, i+1, inr);
  ans.push_back(pre[prel]);
}
int main(){
  int n, i;
  cin>>n;
  vector<int> pre(n), in(n);
  for(i=0; i<n; i++) cin>>pre[i];
  for(i=0; i<n; i++) cin>>in[i];
  dfs(pre, in, 0, 0, n-1);
  cout<<ans[0]<<endl;
  return 0;
}
#include<iostream>
#include<vector>
using namespace std;
bool flag=true;
vector<int> ans;
void dfs(vector<int> pre, vector<int> in, int prel, int inl, int inr){
  int i=inl;
  if(inl>inr || !flag) return;
  while(in[i]!=pre[prel]&&i<inr) i++;
  dfs(pre, in, prel+1, inl, i-1);
  dfs(pre, in, prel+1+i-inl, i+1, inr);
  if(flag){
    cout<<pre[prel];
    flag=false;
  }
}
int main(){
  int n, i;
  cin>>n;
  vector<int> pre(n), in(n);
  for(i=0; i<n; i++) scanf("%d", &pre[i]);
  for(i=0; i<n; i++) scanf("%d ", &in[i]);
  dfs(pre, in, 0, 0, n-1);
  return 0;
}
#include<iostream>
#include<vector>
using namespace std;
bool flag=true;
vector<int> ans;
void dfs(vector<int> &pre, vector<int> &in, int prel, int inl, int inr){
  int i=inl;
  if(inl>inr || !flag) return;
  while(in[i]!=pre[prel]) i++;
  dfs(pre, in, prel+1, inl, i-1);
  dfs(pre, in, prel+1+i-inl, i+1, inr);
  if(flag){
    cout<<pre[prel];
    flag=false;
  }
}
int main(){
  int n, i;
  cin>>n;
  vector<int> pre(n), in(n);
  for(i=0; i<n; i++) cin>>pre[i];
  for(i=0; i<n; i++) cin>>in[i];
  dfs(pre, in, 0, 0, n-1);
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9142486.html