首页 技术 正文
技术 2022年11月12日
0 收藏 329 点赞 2,691 浏览 1572 个字

To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. 
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).

Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree. 
However, doing the reconstruction by hand, soon turned out to be tedious. 
So now she asks you to write a program that does the job for her!

题意:输入先序遍历,中序遍历,输出后序遍历。(看完之后如果不太理解可以看我下一篇随笔,后续我会更新具体思考过程)

解题思路:1.首先需要根据先序遍历和中序遍历创建二叉树

     我们这里需要递归来实现,二叉树问题和递归联系非常紧密。

      BitTree *createBinTreeByPreIn(char *pre,char *in,int number);

      函数需要三个参数:先序遍历字符串(*pre),和中序遍历的字符串(*in),字符串个数(number)。

      结束条件:当字符串长度为0时结束;

 BitTree *createBinTreeByPreIn(char *pre,char *in,int number)
{
if(number==) return NULL;
char c = pre[];
int i = ;
while(i<number && in[i]!=c)i++;
int leftNumber = i;
int rightNumber = number - i - ;
BitTree *node = (BitTree *)malloc(sizeof(BitTree));
node->data = c;
node->lchild = createBinTreeByPreIn(&pre[],&in[],leftNumber);
node->rchild = createBinTreeByPreIn(&pre[leftNumber+],&in[leftNumber+],rightNumber);
return node;
}

     2.后续遍历二叉树

 void PostOrder(BitTree *bt)
{
if(bt!=NULL)
{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
printf("%c",bt->data);
}
}

最后加上主函数来测试我们的程序

 int main(int argc,char **argv)
{
char a[SIZE],b[SIZE];
BitTree *p;
while(scanf("%s%s",a,b)!=EOF)
{
p = createBinTreeByPreIn(a,b,strlen(a));
PostOrder(p);
printf("\n");
}
return ;
}

     

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,122
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,594
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,439
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,210
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,846
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,931