• PAT Advanced 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 (<=50000), 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. postFirst函数本质是建树过程,找到后序遍历的第一个节点后退出以节省时间(后序第一个节点为递归过程中第一个左子节点和右子节点都为NULL的节点)

    易错点

    该题节点数最多为50000个,若在找到后没有退出(即:完成建树过程)会超时

    Code

    Code 01

    #include <iostream>
    #include <vector>
    const int maxn = 50000;
    struct node {
    	int data;
    	node * left;
    	node * right;
    };
    int n,pre[maxn],in[maxn];
    bool flag;
    void postFirst(int inL,int inR, int preL,int preR) {
    	if(inL>inR||flag) return;
    	int k=inL;
    	while(k<inR&&in[k]!=pre[preL])k++;
    	postFirst(inL, k-1, preL+1, preL+(k-inL));
    	postFirst(k+1, inR, preL+(k-inL)+1, preR);
    	if(flag==false) {
    		printf("%d", pre[preL]);
    		flag=true; 
    	}
    }
    int main(int argc,char * argv[]) {
    	scanf("%d",&n);
    	for(int i=0; i<n; i++)scanf("%d",&pre[i]);
    	for(int i=0; i<n; i++)scanf("%d",&in[i]);
    	postFirst(0,n-1,0,n-1);
    }
    
  • 相关阅读:
    美团深度学习系统的工程实践
    Netty堆外内存泄露排查与总结
    美团点评基于 Flink 的实时数仓建设实践
    基于TensorFlow Serving的深度学习在线预估
    前端安全系列之二:如何防止CSRF攻击?
    Logan:美团点评的开源移动端基础日志库
    前端安全系列(一):如何防止XSS攻击?
    beeshell —— 开源的 React Native 组件库
    ES(一): 架构及原理
    Kibana6安装使用(windows)
  • 原文地址:https://www.cnblogs.com/houzm/p/12319092.html
Copyright © 2020-2023  润新知