• 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);
    }
    
  • 相关阅读:
    NYOJ 158 省赛来了(变相组合数)
    NYOJ 111 分数加减法
    NYOJ 14 会场安排问题 (贪心)
    POJ 3903 Stock Exchange(LIS)
    NYOJ 456 邮票分你一半(01背包)
    HDU 4521 小明系列问题——小明序列 (LIS加强版)
    CSU 1120 病毒(经典模板例题:最长公共递增子序列)
    挑战程序设计竞赛里面的几道深度优先搜索
    2009 Multi-University Training Contest 4
    USACO sec1.1
  • 原文地址:https://www.cnblogs.com/houzm/p/12319092.html
Copyright © 2020-2023  润新知