一个二叉树的实现(C版)

二叉树是一种很常见的数据结构,特别是二叉搜索树,如果在插入的时候组建二叉树的话,在搜索的时候可以达到很高的速度。下面我把自己实现的一个二叉搜索树的源码贴出来,大家可以参考一下。

 

先看数据结构的定义:

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等我打包到附件中,需要的朋友可以自行下载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值