问题 A: 复原二叉树
题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG BCAD CBAD
样例输出
ACBFGED CDAB
AC代码:
#include<cstdio>
#include<cstring>
using namespace std;
struct node{
char data;
node* lchild;
node* rchild;
};
int cnt;
char str[101];//用于存放先序字符串
node* create(){
node* root=NULL;
if(str[cnt]=='#'){
root=NULL;
cnt++;
}else{
root = new node;
root->data = str[cnt];
cnt++;
root->lchild = create();
root->rchild = create();
}
return root;
}
void inorder(node * root){
if(root == NULL){
return ;
}
inorder(root->lchild);//访问左子树
printf("%c ",root->data);//访问根结点
inorder(root->rchild);//访问右子树
}
int main(){
while(scanf("%s",str)!=EOF){
cnt=0;
node* root;
root=create();
inorder(root);
printf("\n");
}
return 0;
}
/**************************************************************
Problem: 2014
User: 2015212040209
Language: C++
Result: 正确
Time:0 ms
Memory:1172 kb
****************************************************************/