任务描述
本关任务要求采用中序遍历序列和后序遍历序列构造二叉树。
相关知识
给定一棵二叉树的中序遍历序列和后序遍历序列可以构造出这棵二叉树。例如后序序列是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******/
}
&spm=1001.2101.3001.5002&articleId=144815530&d=1&t=3&u=6289be98b2fb4dd8982a7055774a422c)
4762

被折叠的 条评论
为什么被折叠?



