1096: 复原二叉树

题目链接

                                                  1096: 复原二叉树

时间限制: 1 Sec  内存限制: 32 MB
提交: 103  解决: 77
[提交][状态][讨论版][命题人:外部导入]

题目描述

小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。

输入

输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。

输出

对于每组输入,输出对应的二叉树的后续遍历结果。

样例输入

DBACEGF ABCDEFG
BCAD CBAD

样例输出

ACBFGED
CDAB

思路:了解了中序,先序,后序,层序这些之后,这种题目都是水题。。。

代码: 

#include<iostream>
#include<cstring>
using namespace std;
struct node
{
    char elem;
    node* left;
    node* right;
};
node *create(char *in,char *pre,int l){
    if(l==0) return NULL;
    node *root=new node;
    root->elem=*pre;
    int i=0;
    for(;i<l;i++){
        if(in[i]==*pre) break;
    }
    root->left=create(in,pre+1,i);
    root->right=create(in+i+1,pre+i+1,l-i-1);
    return root;
}
void print(node *root){
    if(root==NULL) return;
    print(root->left);
    print(root->right);
    cout<<root->elem;
}
int main()
{
    int t;
    char in[10000],pre[10000];
    while(cin>>pre>>in){
        t=strlen(in);
        node *stp=new node;
        stp=create(in,pre,t);
        print(stp);
        cout<<endl;
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/DaDaguai001/article/details/81532555