二叉树遍历
来源:互联网 发布:重庆seo网站推广 编辑:程序博客网 时间:2024/06/07 15:39
/*已知前序和中序,得到后序**/#include <stdio.h>#include <string.h>struct Node { Node *lchild ; //左儿子指针 Node *rchild ; //右儿子指针 char c; //结点字符信息 }Tree[50]; //静态内存分配数组 int loc; //静态数组中已经分配的节点个数 Node* create() { Tree[loc].lchild = Tree[loc].rchild = NULL; return &Tree[loc ++];}char str1[30], str2[30];void postOrder(Node *T ) { //后序遍历 if(T -> lchild != NULL) { //左子树不空 postOrder(T -> lchild ); } if(T -> rchild != NULL) { postOrder(T -> rchild ); } printf("%c",T -> c);}Node *build (int s1, int e1, int s2, int e2) { Node *ret = create(); //为该树根节点申请空间 ret ->c = str1[s1]; //该节点字符为前序遍历中第一个字符 int rootIdx; for(int i =s2; i <=e2; i++) { if(str2[i] == str1[s1]) { rootIdx = i; //找到根节点在中序遍历中的位置 break; } } if(rootIdx != s2) { //若左子树不为空 ret -> lchild = build(s1 +1, s1 +(rootIdx -s2), s2, rootIdx-1); } if(rootIdx != e2) { //若右子树不为空 ret ->rchild = build(s1+(rootIdx-s2) +1, e1, rootIdx+1, e2); } return ret;}int main() { while(scanf("%s",str1) != EOF ) { //输入前序遍历 scanf("%s",str2); //输入中序遍历 loc = 0; //初始化静态内存空间中已经使用节点个数为0 int L1 = strlen(str1); int L2 = strlen(str2); //计算两个字符串长度 Node *T = build (0, L1-1, 0, L2-1); //还原整棵树,其根节点指针保存在 T 中 postOrder(T ); //后序遍历 printf("\n"); } return 0;}
/*输出结果:
ABC
BAC
BCA
FDXEAG
XDEFAG
XEDGAF
*/
阅读全文
0 0
- 二叉树遍历、分层遍历
- 遍历二叉树--二叉树
- 【树】遍历二叉树
- 二叉树遍历
- 二叉树遍历
- 二叉树的遍历
- (原创)遍历二叉树
- 二叉树遍历-php
- 查找--遍历二叉树
- 遍历二叉树
- 二叉树遍历规则
- 二叉树的遍历
- 二叉树遍历
- 遍历二叉树
- 二叉树遍历问题
- 二叉树遍历
- 二叉树遍历(zz)
- 二叉树的遍历
- android 6.0
- 自动驾驶--Visual-Inertial-Semantic Scene Representation for 3D object Detection (一 )
- 搭建Framework开发环境
- 机器人学习Robot Learning之模仿学习Imitation Learning的发展
- JQuery动画
- 二叉树遍历
- 企业级容器云平台EcOS-Newben更新至3.0版,全面支持主控节点的高可用
- 阿里云上部署tomcat启动后,通过http不能访问
- setInterval的函数有多个参数导致的失效问题
- HDU5442 Favorite Donut(KMP+最大表示法)
- 外派的这半年
- Qt程序打包发布方法(使用官方提供的windeployqt工具)
- 文章标题
- myBatis配置实现数据库字段下划线映射到java对象的驼峰式命名属性