BOOL cmp(char * s, char * t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if ( s[i] == '\0' )
return NO;
return (s[i] - t[i]) < 0 ? NO:YES;
}
void mystrcpy(char *s, char *t)
{
while ((*s++ = *t++) != '\0')
;
}
void insert(node ** tree, char * val) {
node * temp = NULL;
if(!(*tree)) {
temp = (node*)malloc(sizeof(node));
temp->left = temp->right = NULL;
//temp->str = val; //issue code ...
mystrcpy(temp->str,val);
temp->count = 1;
*tree = temp;
return ;
}
if(cmp(val, (*tree)->str)) {
insert(&(*tree)->left,val);
}else if (cmp(val,(*tree)->str)) {
insert(&(*tree)->right,val);
}else{
(*tree)->count++;
}
}
void deltree(node * tree) {
if(tree) {
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
void print_inorder(node * tree) {
if(tree) {
print_inorder(tree->left);
printf("[%s\t\t\t]count:[%d]\n",tree->str,tree->count);
print_inorder(tree->right);
}
}
int main(int argc, char ** argv)
{
node * root;
node * tmp;
//int i;
root = NULL;
/* Inserting nodes into tree */
insert(&root,"hello");
insert(&root,"hey");
insert(&root,"hello");
insert(&root,"ok");
insert(&root,"hey");
insert(&root,"hey");
insert(&root,"hey");
printf("In Order Display\n");
print_inorder(root);
/* Deleting all nodes of tree */
deltree(root);
}
最后运行结果如下:
Discussion
那么这个程序已经完成啦!
还有很多可以优化的,也可以增加更多的功能;