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 }
  • 相关阅读:
    ASP.NET 5 Web Api 集成测试
    EF 7.0 Beta8 实现简单Unit Of Work 模式
    C#与闭包(closure)学习笔记
    异步初探
    BUBI架构之旅【目录】
    【第2期】如何将NameNode和SecondaryNameNode分开不同节点
    【第1期】使用Docker虚拟化技术搭设Hadoop环境
    【第3期】Linux安装数据库oracle 11g
    【第2期】vsftpd的安装与使用
    【第1期】安装Linux服务器(DB主机与ETL主机)
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/11287976.html
Copyright © 2011-2022 走看看