A1138 Postorder Traversal (25 point(s))

先序+中序=树

1. 原文

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:

1
2
3
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6

Sample output:

1
3

2. 解析

先序 根 左 右

中序 左 根 右

后序 左 右 根

故根据先序的根在中序中固定左子树的位置

  • 左子树=1 便得到结果

  • 左子树>1 查找左子树

  • 左子树=0 左子树不存在,查找右子树

  • 右子树=1 得到结果

  • 右子树>1 查找右子树

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<cstdio>
#include<vector>
using namespace std;
vector<int> in,pre;
void postorder(int inl,int inr,int prel,int prer)
{
if (inl>inr)
{
return;
}
int i=inl;
while(in[i]!=pre[prel]&&i<=inr){
i++;
}
int left=i-inl;
int right=inr-i;
if (left==1)
{
printf("%d\n",in[inl]);
}
else if (left>1)
{
postorder(inl,i-1,prel+1,prel+left);
}else if(right==1){
printf("%d\n",in[inr]);
}else if (right>1)
{
postorder(i+1,inr,prel+left+1,prer);
}

}
int main()
{
int n;
scanf("%d",&n);
int a;
for(int i=0;i<n;i++){
scanf("%d",&a);
pre.push_back(a);
}
for(int i=0;i<n;i++){
scanf("%d",&a);
in.push_back(a);
}
postorder(0,n-1,0,n-1);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/02/A1138/
  • 发布时间: 2019-09-02 19:54
  • 更新时间: 2021-10-29 14:10
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!