PAT (Advanced Level) Practice A1119 Pre- and Post-order Traversals (30 分)(已知前序、後序求中序)

原題鏈接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 50, INF = 1<<30;

typedef struct BiTNode
{
    int data, height;
    struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;

int Pre[MAX], Post[MAX], In[MAX];
int N, cnt = 0;
bool flag = 0;

void getIn(int preL, int preR, int postL, int postR)
{
    if(preL == preR)
    {
        In[cnt++] = Pre[preL];
        return ;
    }
    int k = preL+1;
    while(k <= preR && Pre[k] != Post[postR-1]) k++;
    if(k > preR) return ;
    if(k - preL > 1) getIn(preL+1, k-1, postL, postL+k-preL-2);
    else flag = 1;//此時該節點放在當前節點的左右子樹都可以,這裏放在了右子樹
    In[cnt++] = Pre[preL];//按中序存儲
    getIn(k, preR, postL+k-preL-1, postR-1);
}

int main()
{
    scanf("%d", &N);
    for(int i=0; i<N; i++) scanf("%d", &Pre[i]);
    for(int i=0; i<N; i++) scanf("%d", &Post[i]);
    getIn(0, N-1, 0, N-1);
    if(flag) printf("No\n");
    else printf("Yes\n");
    printf("%d", In[0]);
    for(int i=1; i<cnt; i++) printf(" %d", In[i]);
    printf("\n");//頭一次遇見最後沒回車報格式錯誤的……
	return 0;
}





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