任务描述
本关任务要求采用中序遍历序列和后序遍历序列构造二叉树。
相关知识
给定一棵二叉树的中序遍历序列和后序遍历序列可以构造出这棵二叉树。例如后序序列是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*****/
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******/
}