二叉树遍历序列还原

给出二叉树的中序遍历序列和后序遍历序列,编程还原该二叉树。

输入:
  第1行为二叉树的中序遍历序列
  第2行为二叉树的后序遍历序列

输出:
  二叉树的按层遍历序列

 测试输入关于“测试输入”的帮助期待的输出关于“期待的输出”的帮助时间限制关于“时间限制”的帮助内存限制关于“内存限制”的帮助额外进程关于“{$a} 个额外进程”的帮助
测试用例 1以文本方式显示
  1. badcfeg↵
  2. bdfgeca↵
以文本方式显示
  1. abcdefg↵
1秒64M0
测试用例 2以文本方式显示
  1. cbdafeg↵
  2. cbdfgea↵
以文本方式显示
  1. adebfgc↵
1秒64M0
测试用例 3以文本方式显示
  1. edcba↵
  2. edcba↵
以文本方式显示
  1. abcde↵
1秒64M0
测试用例 6以文本方式显示
  1. bdfgeca↵
  2. gfedcba↵
以文本方式显示
  1. abcdefg↵
1秒64M0
#include<stdlib.h>  
#include<iostream>     
#include<queue>   
#include<string>   
using namespace std;  
  
typedef struct BTN{  
    char d;  
    struct BTN *lc;  
    struct BTN *rc;  
}ne,*nep;  
  
void creattree(nep &root,string inorder,string postorder)  
{  
    if(inorder.length()==0) return;  
    char data=postorder[postorder.length()-1]; //后序序列的尾部即为根结点   
    int sst=inorder.find(data); //返回中序序列里根结点的下标   
    string lci,rci,lcp,rcp;  //左右结点的中序后序  
    int llength=sst,rlength=inorder.length()-sst-1;  //左右结点长度   
    lci=inorder.substr(0,sst);  
    rci=inorder.substr(sst+1);  
    lcp=postorder.substr(0,sst);  
    rcp=postorder.substr(llength,rlength);  
    root=(nep)malloc(sizeof(ne));  
    root->d=data;  
    root->lc=NULL;  
    root->rc=NULL;  
    creattree(root->lc,lci,lcp);  
    creattree(root->rc,rci,rcp);  
    return;  
}  
  
void traverse(nep root)  
{  
    queue<nep> l;  
    nep out=root;  
    l.push(out);  
    while(!l.empty())  
    {  
        out=l.front();  
        printf("%c",out->d);  
        l.pop();  
        if(out->lc) l.push(out->lc);  
        if(out->rc) l.push(out->rc);  
    }  
    printf("\n");  
    return;  
}  
  
int main(){  
    nep root;  
    string inorder,postorder;  
    getline(cin,inorder);  
    getline(cin,postorder);  
    creattree(root,inorder,postorder);  
    traverse(root);  
    return 0;  
}  

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值