輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並輸出它的後序遍歷序列。測試
輸入可能包含多個測試樣例,對於每一個測試案例,spa
輸入的第一行爲一個整數n(1<=n<=1000):表明二叉樹的節點個數。code
輸入的第二行包括n個整數(其中每一個元素a的範圍爲(1<=a<=1000)):表明二叉樹的前序遍歷序列。blog
輸入的第三行包括n個整數(其中每一個元素a的範圍爲(1<=a<=1000)):表明二叉樹的中序遍歷序列。input
對應每一個測試案例,輸出一行:it
若是題目中所給的前序和中序遍歷序列能構成一棵二叉樹,則輸出n個整數,表明二叉樹的後序遍歷序列,每一個元素後面都有空格。io
若是題目中所給的前序和中序遍歷序列不能構成一棵二叉樹,則輸出」No」。class
8 1 2 4 7 3 5 6 8 4 7 2 1 5 3 8 6 8 1 2 4 7 3 5 6 8 4 1 2 7 5 3 8 6
7 4 2 5 8 6 3 1 No
#include <stdio.h> #include <stdlib.h> #include <memory.h> int findRoot(int *arr1,int begin1,int end1,int *arr2,int begin2,int end2,int *final); int final[1000]; int flag = 999; int main(void){ int n,i; int arr1[1000]; int arr2[1000]; while(scanf("%d",&n) != EOF && n <= 1000 && n >= 1){ //initialize memset(arr1,0,sizeof(int)*1000); memset(arr2,0,sizeof(int)*1000); memset(final,0,sizeof(int)*1000); flag = 999; //input for(i=0;i<n;i++) scanf("%d",&arr1[i]); for(i=0;i<n;i++) scanf("%d",&arr2[i]); if(findRoot(arr1,0,n-1,arr2,0,n-1,final) == 0) printf("No\n"); else{ for(i=flag+1;i<1000;i++) printf("%d ",final[i]); printf("\n"); } } return 0; } int findRoot(int *arr1,int begin1,int end1,int *arr2,int begin2,int end2,int *final){ int i,j; int sum = 0; if(begin1==end1 && begin2 == end2){ final[flag] = arr1[begin1]; flag--; return 1; } for(i=begin1 ; i<=end1;i++){ for(j=begin2 ; j <=end2 ; j++){ if(arr1[i] == arr2[j]) sum++; } } if(sum != (end1-begin1+1) && sum != (end2 - begin2+1)){ return 0; } final[flag] = arr1[begin1]; flag--; int numberofRoot = -1; for(i=begin2 ; i<=end2 ; i++){ if(arr1[begin1] == arr2[i]){ numberofRoot = i; //printf("找到跟在arr2的座標爲%d\n",numberofRoot); break; } } if(numberofRoot != end2){ //printf("right %d %d %d %d\n",begin1+numberofRoot-begin2+1,end1,numberofRoot+1,end2); if(!findRoot(arr1,begin1+numberofRoot-begin2+1,end1,arr2,numberofRoot+1,end2,final)){ return 0; } } if(numberofRoot != begin2){ //printf("left %d %d %d %d\n",begin1+1,begin1+numberofRoot-begin2,begin2,numberofRoot-1); if(!findRoot(arr1,begin1+1,begin1+numberofRoot-begin2,arr2,begin2,numberofRoot-1,final)){//左子樹 return 0; } } return 1; }