-
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{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)):代表二叉樹的中序遍歷序列。
- 輸出:
-
對應每個測試案例,輸出一行:
#include <iostream> #include <string> #include <vector> using namespace std; struct BinaryTree { int value; BinaryTree *left; BinaryTree *right; }; BinaryTree*constructBTN(int *preorder,int *preendorder,int *midorder,int*midendorder); BinaryTree *b_t_c(int *pre,int *mid,int len) { if (pre==NULL||mid==NULL||len<0)//前序中序存在 { return NULL; } return constructBTN(pre,pre+len-1,mid,mid+len-1);//前序中序的首末地址 } BinaryTree*constructBTN(int *preorder,int *preendorder,int *midorder,int*midendorder) { int root_value=preorder[0]; BinaryTree* btree=new BinaryTree(); btree->value=root_value; btree->left=NULL; btree->right=NULL; if (preorder==preendorder&&midorder==midendorder&&*preorder==*midorder)//首末地址相同 只有一個節點 { return btree; } int *rootIndex=midorder;//取中序首地址 while(*rootIndex!=root_value&&rootIndex<=midendorder)//中序中尋找根節點 { rootIndex++; } if (*rootIndex!=root_value&&rootIndex!=midendorder)//沒有找到 { cout<<"NO"<<endl; return NULL; } int left_len=rootIndex-midorder;//在中序中找到根節點地址,減去中序啓示節點地址 int *left_pre_end=preorder+left_len;//前序遍歷中得到左半部分 if (left_len>0) { btree->left=constructBTN(preorder+1,left_pre_end,midorder,rootIndex-1); if (btree->left==NULL) { return NULL; } } if (left_len<preendorder-preorder) { btree->right=constructBTN(left_pre_end+1,preendorder,rootIndex+1,midendorder); if (btree->right==NULL) { return NULL; } } return btree; } void printbtn(BinaryTree* root) { if (root!=NULL) { printbtn(root->left); printbtn(root->right); cout<<root->value<<" "; } } int main() { while(1) { int num; cin>>num; int qian[100]; int zhong[100]; memset(qian,0,sizeof(qian)); memset(zhong,0,sizeof(zhong)); int value; for (int i=0;i<num;i++) { cin>>qian[i]; } for (int i=0;i<num;i++) { cin>>zhong[i]; } BinaryTree *proot=b_t_c(qian,zhong,num); printbtn(proot); } return 0; }
如果題目中所給的前序和中序遍歷序列能構成一棵二叉樹,則輸出n個整數,代表二叉樹的後序遍歷序列,每個元素後面都有空格。
如果題目中所給的前序和中序遍歷序列不能構成一棵二叉樹,則輸出”No”。
- 樣例輸入:
-
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
-
-
-