数据结构实验之求二叉树后序遍历和层次遍历
2013-02-20 09:50
281 查看
先根据先序遍历和终须遍历的关系建立起树杈模型,之后 这题的关键是层次遍历,根据队列的原理一层一层的从左向右出来,上一层的决定下一层的;二叉树比较方便的是只要左右,所以最多两次,还有就是有可能树杈为空所以注意为空的判断条件。
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct node { char data; struct node *lc,*rc; }tree,*tree1; tree1 build(char *xian,char *zhong,int k) { tree1 t; if(k <= 0) { return NULL; } char *p; int m; t = (tree1)malloc(sizeof(tree)); t -> data = *xian; for(p = zhong ;; p++) if(*p == *xian) break; m = p-zhong; t->lc = build(xian+1,zhong,m) ; t->rc = build(xian+m+1,p+1,k-m-1); return t; } void hx (tree1 t) { if(t != NULL) { hx(t -> lc); hx(t -> rc); printf("%c",t -> data); } } void ceng (tree1 t)//这里是层遍历; { int q,h;//q代表每一层的两个分叉,h代表下一层的叉,h由q决定; tree *p[100]; p[0]=t; h=1; q=0; while(h > q) { if( p[q] ) { printf("%c",p[q] -> data); p[h] = p[q] -> lc;//先左后右; h++;//个数加1,层数不变; p[h] = p[q] -> rc; h++;//个数层数都加1; q++; } else { q++;//不满足条件直接就层数加1; } } } int main() { int n,k; char xian[100],zhong[100]; scanf("%d",&n); while(n--) { scanf("%s%s",xian,zhong); tree1 t; k = strlen(xian); t = build(xian, zhong, k); hx( t ); printf("\n"); ceng (t); printf("\n"); } return 0; }连接 http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2137&cid=1145
相关文章推荐
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历(简单版)
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历 分类: 树 2015-06-21 10:58 11人阅读 评论(0) 收藏
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历