数据结构上机测试4.1:二叉树的遍历与应用1(先序+中序==后序)

Problem Description

输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。

Input

第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。

Output

输出该二叉树的后序遍历序列。

Sample Input

ABDCEF
BDAECF

Sample Output

DBEFCA

Hint

Source

题解:根据先序和中序序列建立起二叉树,然后后序遍历即可。

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    char data;
};
node *create(char *previous,char *middle,int len)
{
    if(len<=0)
        return NULL;  //空节点
    node *root;
    root=new node;
    root->data=previous[0];  //先序遍历,第一个肯定是根节点,如此迭代
    int i;
    for(i=0;i<len;i++)
    {
        if(middle[i]==previous[0]) //找到中序的该根节点,并依次迭代
            break;
    }
    root->l=create(previous+1,middle,i); //左子树中先序遍历字串向后挪一位,中序不变,但i控制了长度
    root->r=create(previous+i+1,middle+i+1,len-i-1);//右子树中先序遍历和中序遍历都向后挪i+1位,长度变成总长度减去前半部分的长度(注意+1)
    return root;
}
void finallshow(node *root)
{
    if(root)
    {
        finallshow(root->l);
        finallshow(root->r);
        cout<<root->data;
    }
}
int main()
{
    node *root;
    char previous[100],middle[100];
    cin>>previous>>middle;  //先序中序
    int len=strlen(previous); //都一样
    root=create(previous,middle,len); //将树建起来后序遍历即可
    finallshow(root);
    cout<<endl;
    return 0;
}


/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 196KB
Submit time: 2019-02-24 22:18:39
****************************************************/

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值