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 }
  • 相关阅读:
    IIS文件大小限制
    XAMPP 配置多端口 多站点
    C# 复制文件和文件夹
    Windows下 Python 安装包的配置
    从数据库读取数据绑定到TreeView(内含设置样式,图片)
    异步请求数据简单例子
    Jmeter使用_StringFromFile函数需要添加编码方式
    利用Fitnesse和Jmeter实现接口性能测试
    简易覆盖率信息收集框架
    如何对遗留代码进行单元测试(scrumgathering听后感)
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/11287976.html
Copyright © 2011-2022 走看看