PAT甲級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. 我們 前序 後序深搜時候,1 2 3 4 5 6 7 ,2 3 1 5 4 7 6兩個數列,先分析出來了根節點爲1
  2. 根據1在中序裏面的位置,可知左子樹的中序 爲2 3,右子樹的中序爲 5 4 7 6
  3. 然後因爲我們只要求後序遍歷的第一個元素,那麼在左右子樹都存在的情況只關注左子樹,只存在右子樹則只關注右子樹,即 前序 2 3,中序也是2 3。
  4. 然後和開頭一樣,先分析出根節點爲2,左子樹爲空,右子樹爲3,那麼在僅僅右子樹存在的情況只關注右子樹,所以這個3就是我們所求的後序遍歷的第一個元素。

實現代碼如下:

#include <iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;

int sn1[50001];
int sn2[50001];

int  df(int N,int sn1S,int sn2S){
    //sn1 是前序 sn2是中序
    int root=sn1[sn1S];
    int rootPos=sn2S;
    while(sn2[rootPos]!=root)
        rootPos++;
    //左子樹的個數是 rootPos-rightS
    int leftNumber=rootPos-sn2S;
    int rightNumber=N-1-leftNumber;
    //題目就是求後序遍歷的第一個元素,那麼同時有左右子樹,遍歷左子樹 沒有左子樹了才遍歷右子樹
    if(leftNumber>1){// 左子樹有兩個及兩個以上的元素,還需要遞歸分析左子樹
        df(leftNumber,sn1S+1,sn2S);
    }
    else if(leftNumber==1){//左子樹只有一個元素就是我們所求的元素了
        return sn2[sn2S];
    }
    else if(rightNumber>1){
        df(rightNumber,sn1S+1,rootPos+1);
    }
    else if(rightNumber==1){
         return sn2[rootPos+1];
    }
    else
        return -1;
}
int main()
{
    int N;
    cin>>N;
    for(int i=0; i<N; i++)
    {
        cin>>sn1[i];
    }
    for(int i=0; i<N; i++)
    {
        cin>>sn2[i];
    }
   cout<<df(N,0,0);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章