[二叉树建树] 复原二叉树(前序遍历和中序遍历构建二叉树)

题目描述

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

输入

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

输出

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

样例输入

DBACEGF ABCDEFG BCAD CBAD

样例输出

ACBFGED CDAB
 
TODO:you need to add your analysis in here.
 
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

struct node
{
    char data;
    int layer;
    node * lchild,*rchild;
};

string prestr,instr;

node * creat(int preL,int preR,int inL,int inR)
{
    if(preL>preR) return NULL;
    node * root = new node;
    root->data=prestr[preL];
    int k;
    //在中序输出中找到preL的字符
    for(k=inL;k<=inR;k++)
    {
        if(instr[k]==prestr[preL]) break;
    }
    int numLeft=k-inL;
    root->lchild=creat(preL+1,preL+numLeft,inL,k-1);
    root->rchild=creat(preL+numLeft+1,preR,k+1,inR);
    return root;
}

void postOrder(node * root)
{
    if(root==NULL)
    {
        return ;
    }
    postOrder(root->lchild);
    postOrder(root->rchild);
    cout<<root->data;
}



int main() 
{
    while(cin>>prestr>>instr)
    {
        node * root;
        root=creat(0,prestr.length()-1,0,instr.length()-1);
        postOrder(root);
        cout<<endl;
    }
    return 0;
}

 

 
 
 
posted @ 2017-02-22 17:43  Num.Zero  阅读(1767)  评论(0编辑  收藏  举报