1. 程式人生 > >pat 甲級1138 後序遍歷的第一個元素

pat 甲級1138 後序遍歷的第一個元素

題目描述:

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

這道題題目翻譯出來很簡單,給定一棵書的先序遍歷和後序遍歷,然後找出這棵樹後序遍歷的第一個元素,考察資料結構知識吧。我的思路是先找到根,然後不停找左子樹,如果發現當前的根已經沒有左子樹了,就轉而去找右子樹的左子樹,以此類推,知道找到葉子結點。程式碼如下:

#include<iostream>
using namespace std;
int main(){
    int N;
    cin>>N;
    int pre[50001],in[50001];
    int istra[50001]={0};
    for(int i=0;i<N;i++)
        cin>>pre[i];
    for(int i=0;i<N;i++)
        cin>>in[i];
    int n=N,prep=0,start=0;
    int ans=0;
    while(true){
        int i;
        for(i=start;i<n;i++)
            if(in[i]==pre[prep])
                break;
        if(i!=start) n=i;
        istra[i]=1;
        if((i-1==-1||istra[i-1]==1)&&(i+1==N||istra[i+1]==1)){
            ans=i;
            break;
        }
        if(i-1==-1||istra[i-1]==1)
            start=i+1;
        prep++;
    }
    cout<<in[ans];
    return 0;
}