浏览 4014 次
锁定老帖子 主题:一个二叉树的实现(C版)
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-04-08
二叉树是一种很常见的数据结构,特别是二叉搜索树,如果在插入的时候组建二叉树的话,在搜索的时候可以达到很高的速度。下面我把自己实现的一个二叉搜索树的源码贴出来,大家可以参考一下。
先看数据结构的定义: bintree.h #include <stdio.h> struct tnode{ char *word; int count; struct tnode *left; struct tnode *right; }; struct tnode *addtree(struct tnode *,char *); void treeprint(struct tnode *); 头文件中定义了数据结构和两个函数,相当于接口的定义,下面是具体的实现: bintree.c #include <stdlib.h> #include <string.h> #include "bintree.h" struct tnode *addtree(struct tnode *p,char *w) { int cond; if(p == NULL){ p = (struct tnode *)malloc(sizeof(struct tnode)); p->word = strdup(w); p->count = 1; p->left = p->right = NULL; }else if((cond = strcmp(w,p->word)) == 0) p->count++; else if(cond < 0) p->left = addtree(p->left,w); else p->right = addtree(p->right,w); return p; } //下面分别为三种遍历树的方式,中序,前序和后序遍历 void treeprint(struct tnode *p) { if(p != NULL){ treeprint(p->left); fprintf(stdout,"%s : %4d\n",p->word,p->count); treeprint(p->right); } } void treeprint2(struct tnode *p) { if(p != NULL){ fprintf(stdout,"%s : %4d\n",p->word,p->count); treeprint(p->left); treeprint(p->right); } } void treeprint3(struct tnode *p) { if(p != NULL){ treeprint(p->left); treeprint(p->right); fprintf(stdout,"%s : %4d\n",p->word,p->count); } } 好了,下边是一个测试函数:
main.c #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include "bintree.h" static char *items[] = { "Today","Tomorrow","Tuck","Hello","Mystery","today", "Tuck","Hello","Monday","Monday",NULL }; int main(void) { int i; struct tnode *root; root = NULL; for(i = 0;items[i] != NULL;i++) root = addtree(root,items[i]); treeprint(root); fprintf(stdout,"---------------------------\n"); treeprint2(root); fprintf(stdout,"---------------------------\n"); treeprint3(root); return 0; }
测试结果如下: 结果:
Hello : 2
Monday : 2 Mystery : 1 Today : 1 Tomorrow : 1 Tuck : 2 today : 1 --------------------------- Today : 1 Hello : 2 Monday : 2 Mystery : 1 Tomorrow : 1 Tuck : 2 today : 1 --------------------------- Hello : 2 Monday : 2 Mystery : 1 Tomorrow : 1 Tuck : 2 today : 1 makefile等我打包到附件中,需要的朋友可以自行下载。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |