zoukankan      html  css  js  c++  java
  • 1138 Postorder Traversal (25 分)

    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 (≤ 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 <bits/stdc++.h>
     2 using namespace std;
     3 int n,an[100005],bn[100005];
     4 struct Node{
     5     int val;
     6     Node *left, *right;
     7 }*head;
     8 vector<int> v;
     9 Node* build(int x,int ll, int rr){
    10     // cout <<ll<<" "<<rr<<endl;
    11     int l = 0;
    12     Node *root = (Node*)malloc(sizeof(Node));
    13     root->val = an[x];
    14     root->left = NULL;
    15     root->right = NULL;
    16     for(int i = ll ; i <= rr; i++){
    17         if(bn[i] == an[x]){
    18             l = i;
    19             break;
    20         }
    21     }
    22     if(l > ll){
    23         root->left = build( x+1, ll, l-1);
    24     }
    25     if(l < rr){
    26         root->right = build( x+1+l-ll, l+1, rr);
    27     }
    28     return root;
    29 }
    30 void search(Node *root){
    31     if(root){
    32         search(root->left);
    33         search(root->right);
    34         v.push_back(root->val);
    35     }
    36 }
    37 int main(){
    38     cin >> n;
    39     for(int i = 1; i <= n; i++)
    40         cin >> an[i];
    41     for(int i = 1; i <= n; i++)
    42         cin >> bn[i];
    43     head = build(1,1,n);
    44     search(head);
    45     cout << v[0]<<endl;
    46     return 0;
    47 }
  • 相关阅读:
    js变量类型
    js词法分析
    ORACLE 查找字段在哪些表里存在
    主外键约束的关闭和启用
    pl/sql developer 编码格式设置(转)
    WIN7 Net Configuration Assistant打不开
    Kettle 连接失败 Oracle 数据库报 ora-12505 的解决方法(转)
    正则表达式30分钟入门教程(转)
    设置程序的多个入口,进行动态的显示
    应用多入口配置
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/11287976.html
Copyright © 2011-2022 走看看