|
1003. 二叉樹后序遍歷
|
||||||
|
||||||
|
Description
給定一棵二叉樹的前序和中序遍歷順序,輸出后序遍歷順序
Input
第一行是二叉樹的前序遍歷順序。二叉樹的結點個數<=26,每個結點以一個大寫字母表示,結點字母之間沒有間隔。第二行是這棵二叉樹的中序遍歷順序,表示方法和前序相同。(注:在左子樹和右子樹之間總是先左后右)
Output
輸出二叉樹后序遍歷的順序
Sample Input
GDAFEMHZ ADEFGHMZ
Sample Output
AEFDHZMG |
通過前序遍歷與中序遍歷可以唯一確定二叉樹
我們先重建一棵二叉樹
再后序遍歷
#include <iostream>
#include <string>
using namespace std;
//結點類
struct Node
{
Node * lchild;
Node * rchild;
char c;
};
//重建后續排序二叉樹
Node * rebuild(string s1, string s2)
{
//建立根結點
Node * t=NULL; //一定要初始化為NULL,不然報錯
if(s1.size()>0){
t=new Node;
t->c=s1[0];
t->lchild=NULL;
t->rchild=NULL;
}
if(s1.size()>1){
//尋找根結點在中序遍歷中的位置
int root;
for(int i=0; i<s2.size(); i++){
if(s2[i]==t->c){
root=i;
break;
}
}
//左子樹重建
string qianxu_left=s1.substr(1, root); //注意substr的用法,第二個參數是子字符串長度
string zhongxu_left=s2.substr(0, root);
t->lchild=rebuild(qianxu_left, zhongxu_left);
//右子樹重建
string qianxu_right=s1.substr(root+1, s1.size()-root-1);
string zhongxu_right=s2.substr(root+1, s2.size()-root-1);
t->rchild=rebuild(qianxu_right, zhongxu_right);
}
return t;
}
//后序遍歷:左右根
void houxu(Node * t)
{
//左子樹非空,遍歷左子樹
if(t->lchild!=NULL)
houxu(t->lchild);
//右子樹非空,遍歷右子樹
if(t->rchild!=NULL)
houxu(t->rchild);
//取出該結點的值
cout<<t->c;
}
int main()
{
string s1, s2;
cin>>s1>>s2;
Node * t=rebuild(s1, s2);
houxu(t);
cout<<endl;
return 0;
}

Copy sample input to clipboard