#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXWORD 100
struct tnode
{
struct tnode*left ;
struct tnode*right ;
int count ;
char*word ;
};
struct tnode*addtree(struct tnode*root , char*w)
{
int cond ;
if(root == NULL)
{
root = (struct tnode*)malloc(sizeof(struct tnode));/*书上把这一步封装成了一个函数*/
root->word = strdup(w);
root->count = 1 ;
root->left = NULL;
root->right = NULL;
}
else if((cond = strcmp(root->word,w)) == 0)
root->count++ ;
else if(cond > 0)
root->left = addtree(root->left,w);
else
root->right = addtree(root->right,w);
return root;
}
void treeprint(struct tnode*root)
{
if(root != NULL)
{
treeprint(root->left);
printf("%4d %s\n",root->count,root->word);
treeprint(root->right);
}
}
int main()
{
struct tnode*root = NULL ;
char* a = "now" ;
root = addtree(root,a) ;
char* b = "is" ;
root = addtree(root,b) ;
char* c = "the";
root = addtree(root,c);
char* d ="time";
root = addtree(root,d);
char* e ="for";
root = addtree(root,e);
char* f = "all";
root = addtree(root,f);
char* g = "good";
root = addtree(root,g);
char* h = "men";
root = addtree(root,h);
char* i = "to";
root = addtree(root,i);
char* j = "come";
root = addtree(root,j);
char*k = "to";
root = addtree(root ,k);
char*l = "the";
root = addtree(root,l);
char*m = "aid";
root = addtree(root,m);
char*n = "of";
root = addtree(root,n);
char*o = "their";
root = addtree(root,o);
char*p = "party";
root = addtree(root,p);
treeprint(root);
system("pause");
return 0 ;
}
测试样本为:now is the time for all good men to come to the aid of their party
数形如下:因为这个在线工具https://www.cs.usfca.edu/~galles/visualization/BST.html
设置的输入框中最多只能输入4个字符,所有their和party只能是thei和part
测试结果:
动态演示如下:
二叉树动态演示
当然,我上面代码用的main函数很low,我们完全可以使用getword()函数来替代。时隔三日,我来更新:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXWORD 100
struct tnode
{
struct tnode*left ;
struct tnode*right ;
int count ;
char*word ;
};
struct tnode*addtree(struct tnode*root , char*w)
{
int cond ;
if(root == NULL)
{
root = (struct tnode*)malloc(sizeof(struct tnode));/*书上把这一步封装成了一个函数*/
root->word = strdup(w);
root->count = 1 ;
root->left = NULL;
root->right = NULL;
}
else if((cond = strcmp(root->word,w)) == 0)
root->count++ ;
else if(cond > 0)
root->left = addtree(root->left,w);
else
root->right = addtree(root->right,w);
return root;
}
void treeprint(struct tnode*root)
{
if(root != NULL)
{
treeprint(root->left);
printf("%4d %s\n",root->count,root->word);
treeprint(root->right);
}
}
int getword(char*word,int lim)
{
char* w = word;
int c ;
int getchar(void);
void ungetch(int);
while(isspace(c = getchar()))
;
if(c != EOF)
*w++ = c ;
else if(!isalpha(c))
{
*w = '\0';
return c;
}
for(; --lim >0 ; w++)
{
if(!isalnum(*w = getchar()))
{
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
int main()
{
struct tnode* root = NULL;
int w ;
char word[MAXWORD];
while((w = getword(word,MAXWORD))!=EOF)
{
root = addtree(root,word);
treeprint(root);
system("pause");
}
return 0 ;
}
测试结果如下: