题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
注意
- 学会如何根据
先序序列
和中序序列
构建二叉树 - 学会二叉树的遍历
#include<bits/stdc++.h>
using namespace std;
struct TreeNode{
char data;
TreeNode *left,*right;
TreeNode(char ch):data(ch),left(NULL),right(NULL){}
};
TreeNode* Build(string str1,string str2){
if(str1.size()==0) return NULL;
char c=str1[0];
TreeNode* root=new TreeNode(c);
int position=str2.find(c);
root->left=Build(str1.substr(1,position),str2.substr(0,position));
root->right=Build(str1.substr(position+1),str2.substr(position+1));
return root;
}
void PostOrder(TreeNode* root){
if(root==NULL) return;
PostOrder(root->left);
PostOrder(root->right);
printf("%c",root->data);
}
int main(){
ios::sync_with_stdio(0);
string str1,str2;
while(cin>>str1>>str2){
TreeNode* root=Build(str1,str2);
PostOrder(root);
printf("\n");
}
return 0;
}