头歌实训数据结构与算法-二叉树及其应用(第8关:由中序序列和后序序列构造二叉树)

任务描述


本关任务要求采用中序遍历序列和后序遍历序列构造二叉树。

相关知识


给定一棵二叉树的中序遍历序列和后序遍历序列可以构造出这棵二叉树。例如后序序列是DEBFGCA,中序序列是DBEAFCG,那么这颗二叉树的结构如图1所示。

树结点结构定义为:

struct BTNode{
        char data;
        struct BTNode* lchild;
        struct BTNode* rchild;
};


编程要求
本关任务是实现ConstructTree.cpp里的BTNode* InPostToTree(char *post, char *in, int n)
该函数的功能是由后序遍历序列和中序遍历序列构造二叉树
后序序列为post[0:n-1]
中序序列为in[0:n-1]
返回所构造的二叉树的根指针
提示1:这是一个递归函数,在主程序中调用:
InPostToTree(post,in,n),其中n是序列长度。
提示2:由于在DeleteTree()中是使用delete删除一个树结点,所以在InPostToTree()需要使用new来申请结点空间。

//ConstructTree.cpp
#include "binary_tree.h"
/**
    InPostToTree(): 由后序遍历序列和中序遍历序列构造二叉树
    后序序列为post[0:n-1]
    中序序列为in[0:n-1]
    返回所构造的二叉树的根指针
*/
BTNode* InPostToTree(char *post, char *in, int n);
{
    //在begin和end之间添加你的代码
    /********* begin **********/
    
    /********* end ************/
}
void PrintPreTravel(BTNode* t)
{
    printf("%c", t->data);
    if(t==NULL) return;
    if(t->lchild) PrintPreTravel(t->lchild);
    if(t->rchild) PrintPreTravel(t->rchild);    
}
void DeleteTree(BTNode* t)
{
    if(t==NULL) return;
    if(t->lchild) DeleteTree(t->lchild);
    if(t->rchild) DeleteTree(t->rchild);
    delete t;
}


测试说明
本关的测试过程如下:

平台编译step8/Main.cpp;
平台运行该可执行文件,并以标准输入方式提供测试输入;
平台获取该可执行文件的输出,然后将其与预期输出对比,如果一致则测试通过;否则测试失败。


输入格式:

输入后序序列
输入中序序列

输出格式:

输出前序序列

以下是平台对step8/Main.cpp的测试样例:

样例输入

DEBFGCA
DBEAFCG

样例输出

Pre Travel Result:ABDECFG

开始你的任务吧,祝你成功!

测试代码: 

///////////////////////////////////////////////////////////
#include "binary_tree.h"
/////////////////////////////////////////////////////////////


/**
	InPostToTree(): 由后序遍历序列和中序遍历序列构造二叉树
	后序序列为post[0:n-1]
	中序序列为in[0:n-1]
	返回所构造的二叉树的根指针
*/
BTNode* InPostToTree(char *post, char *in, int n)
{
	/*请在BEGIN和END之间实现你的代码*/
	/*****BEGIN*****/

	/******END******/
}
 

 补充代码:

///////////////////////////////////////////////////////////
#include "binary_tree.h"
/////////////////////////////////////////////////////////////


/**
	InPostToTree(): 由后序遍历序列和中序遍历序列构造二叉树
	后序序列为post[0:n-1]
	中序序列为in[0:n-1]
	返回所构造的二叉树的根指针
*/
BTNode* InPostToTree(char *post, char *in, int n)
{
	/*请在BEGIN和END之间实现你的代码*/
	/*****BEGIN*****/
    BTNode *s;
    char r,*p;
    int k;
    if (n<=0) return NULL;
    r=*(post+n-1);
    s=(BTNode *)malloc(sizeof(BTNode));
    s->data=r;
    for (p=in; p<in+n; p++)
        if (*p==r)
            break;
    k=p-in;
    s->lchild=InPostToTree(post,in,k);
    s->rchild=InPostToTree(post+k,p+1,n-k-1);
    return s;
    	/******END******/
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值