問題 B: 二叉樹的遍歷
時間限制: 1 Sec 內存限制: 128 MB提交: 582 解決: 331
[提交][狀態][討論版]
題目描述
根據二叉樹性質,由二叉樹的前序遍歷序和中序遍歷序,可以唯一確定一棵二叉樹(設二叉樹中各結點不相同)。請編寫程序,根據輸入的二叉樹的前序遍歷序和中序遍歷序,計算並輸出其后序遍歷序。
輸入
輸入第一行為二叉樹的個數n,0<n≤1000,其后n行每行中由兩個字符串組成,第一個是二叉樹的前序遍歷序,第二個是二叉樹的中序遍歷序,字符串中每個字符表示一個結點,字符串長度不超過2000。
輸出
對每個二叉樹,輸出一行后序遍歷序。
樣例輸入
2
abc bac
ab ba
樣例輸出
bca ba
#include "bits/stdc++.h" using namespace std; typedef struct tree1 { char data; tree1 *leftchild; tree1 *rightchild; }*Tree1; void creattree1(Tree1 &T,string s1,string s2) { if(s1.length() == 0) { T = NULL; return; } char roots = s1[0]; int position = s2.find(roots); string leftstr2 = s2.substr(0,position); string rightstr2 = s2.substr(position+1); int lenleft = leftstr2.length(); int lenright = rightstr2.length(); string leftstr1 = s1.substr(1,lenleft); string rightstr1 = s1.substr(lenleft+1); T = (Tree1)malloc(sizeof(tree1)); if(T != NULL) { T->data = roots; creattree1(T->leftchild,leftstr1,leftstr2); creattree1(T->rightchild,rightstr1,rightstr2); } } void houxubianli(Tree1 &T) { if(T == NULL) return; houxubianli(T->leftchild); houxubianli(T->rightchild); cout << T->data; } int main() { int n; cin >> n; while(n--) { Tree1 T; string s1,s2; cin >> s1 >> s2; creattree1(T,s1,s2); houxubianli(T); cout <<endl; } return 0; }
思想是遞歸,蠻難想的,半抄半寫。