C语言实现二叉树创建和查找
#include
#include
#include
#include
#define MAXWORD 100
struct tree_node *addtree(struct tree_node * , char *);
void treeprint(struct tree_node *);
int getword(char * ,int );
//定义二叉树结构
struct tree_node{
char *word ; //指向单词的指针
int *count ; //统计单词出现的次数
struct tree_node * left ; //指向左子树的指针 自引用结构体
struct tree_node * right; //指向右子树指针
};
int main(){
struct tree_node * root;
char word[MAXWORD];
root = NULL;
while (getword(word,MAXWORD) != EOF)
if(isalpha(word[0]))
root = addtree(root,word);
treeprint(root);
return 0;
}
//为新节点分配空间
struct tree_node *tree_alloc(void);
//复制新单词
char *strdup(char *);
struct tree_node * addtree(struct tree_node * p ,char *w)
{
int cond;
if (p == NULL){ //a new word has arrved ;
p = tree_alloc(); //make a new node ;
p->word = strdup(w);
p->count = 1;
p->next = 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;
}
//treeprint 函数按顺序打印树 ==>先打印左子树,然后打印本身,最后后打印右子树
void treeprint(struct tree_node * p)
{
if ( p != NULL){
treeprint(p->left);
printf("%8d %s\n",p->count ,p->word);
treeprint(p->right);
}
}
// 分配新节点所需的空间
//
struct tree_node * tree_alloc(void)
{
return (struct tree_node*) malloc(sizeof(struct tree_node));
}
//strdup 函数通过调用malloc函数把传入的字符串复制到一个安全的位置
char * strdup(char *s)
{
char * p;
p = (char * ) malloc(strlen(s)+1); //多分配一个字节的空间用来存放'\0',strlen函数返回的长度不包含'\0'在内。
if(p != NULL) //可能分配空间会失败,所以先判断一下
strcpy(p ,s);
return p;
}