-
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並輸出它的後序遍歷序列。
- 輸入:
-
輸入可能包含多個測試樣例,對於每個測試案例,
輸入的第一行爲一個整數n(1<=n<=1000):代表二叉樹的節點個數。
輸入的第二行包括n個整數(其中每個元素a的範圍爲(1<=a<=1000)):代表二叉樹的前序遍歷序列。
輸入的第三行包括n個整數(其中每個元素a的範圍爲(1<=a<=1000)):代表二叉樹的中序遍歷序列。
- 輸出:
-
對應每個測試案例,輸出一行:
如果題目中所給的前序和中序遍歷序列能構成一棵二叉樹,則輸出n個整數,代表二叉樹的後序遍歷序列,每個元素後面都有空格。
如果題目中所給的前序和中序遍歷序列不能構成一棵二叉樹,則輸出”No”。
- 樣例輸入:
-
81 2 4 7 3 5 6 84 7 2 1 5 3 8 681 2 4 7 3 5 6 84 1 2 7 5 3 8 6
- 樣例輸出:
-
7 4 2 5 8 6 3 1 No
typedef struct binarytree { int value; binarytree* left; binarytree* right; }Node,*ptrNode; binarytree* Rebuild_Binary(int* prestart,int* preend, int* instart,int* inend ) { ptrNode root=new Node; int key; //if(*prestart) key=prestart[0]; root->value=key; root->left=root->right=NULL; if(*prestart==*preend) { if(*instart==*inend) return root; else printf("Input is error!\n"); return NULL; } int leftnum=0,rightnum; int* ordernum; ordernum=instart; while(*ordernum!=key&&ordernum<inend) { leftnum++; ordernum++; } rightnum=inend-ordernum+1; if(leftnum>0) { root->left=Rebuild_Binary(prestart+1,prestart+leftnum, instart,instart+leftnum-1); } if(rightnum>0) { root->right=Rebuild_Binary(prestart+leftnum+1,preend, instart+leftnum+1,inend); } return root; } ptrNode Creat(int* a,int* b,int len) { return Rebuild_Binary(a,a+len-1,b,b+len-1); } void main() { int a[8]={1,2,4,7,3,5,6,8}; int b[8]={4,7,2,1,5,3,8,6}; ptrNode tree=Creat(a,b,8); }