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 }
  • 相关阅读:
    第一次工作 第一星期问题总结。
    IOS 中使用token机制来验证用户的安全性
    地址栏连接参数修改
    JavaScript反调试技巧
    简谈前端存储
    跨域的原因,场景,方法
    vue学习笔记(一)关于事件冒泡和键盘事件 以及与Angular的区别
    vue入门 vue与react和Angular的关系和区别
    详细图解作用域链与闭包
    jQuery的ajax详解
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/11287976.html
Copyright © 2011-2022 走看看