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

题目描述

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

输入

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

输出

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

样例输入

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;
}

 

 
 
 

转载于:https://www.cnblogs.com/xiongmao-cpp/p/6430085.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值