PAT A1138 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 (≤ 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:

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

Sample Output:

3
 
 1 #include <stdio.h>
 2 #include <iostream>
 3 const int maxn=50010;
 4 struct node{
 5   int data;
 6   node* left,*right;
 7 };
 8 int in[maxn],pre[maxn];
 9 node* create(int prel,int prer,int inl,int inr){
10   if(prel>prer) return NULL;
11   node* root = new node;
12   root->data = pre[prel];
13   int k;
14   for(k=inl;k<=inr;k++){
15     if(in[k]==pre[prel]) break;
16   }
17   int numleft = k-inl;
18   root->left = create(prel+1,prel+numleft,inl,k-1);
19   root->right = create(prel+numleft+1,prer,k+1,inr);
20   return root;
21 }
22 int main(){
23   int n;
24   scanf("%d",&n);
25   for(int i=0;i<n;i++){
26     int d;
27     scanf("%d",&d);
28     pre[i]=d;
29   }
30   for(int i=0;i<n;i++){
31     int d;
32     scanf("%d",&d);
33     in[i]=d;
34   }
35   int prel=0,prer=n-1,inl=0,inr=n-1;
36   int numleft=n;
37   int k;
38   while(numleft!=1){
39         for(k=inl;k<=inr;k++){
40             if(in[k]==pre[prel]) break;
41         }
42         int nl=k-inl;
43         int nr=inr-k;
44         if(nl==0){
45             prel=prel+nl+1;
46             prer=prer;
47             inl=k+1;
48             inr=inr;
49             numleft=nr;
50         }
51         else{
52             prel=prel+1;
53             prer=prel+nl;
54             inl=inl;
55             inr=k-1;
56             numleft=nl;
57         }
58    }
59    printf("%d",in[inl]);
60 }
View Code

注意点:这道题虽然给的时间很多650ms,但直接建树再查找还是会超时,好像可以用引用来避免超时。

不建树其实就是通过两个序列来找到第一个叶子节点,当一个节点的左边或右边只有一个元素时,剩下的那个元素就是要输出的值。

转载于:https://www.cnblogs.com/tccbj/p/10429516.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值