1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
/* trees.c
*
* Trees
*
*/
#include "trees.h"
/* adds a node containing token, at or below p */
struct tnode *bintree_insert(struct tnode *p, char *t)
{
int cond;
if (p == NULL)
{
p = (struct tnode *) malloc(sizeof(struct tnode));
p->text = t;
p->count = 1;
p->left = p->right = NULL;
}
else if ((cond = strcmp(t, p->text)) == 0)
p->count++;
else if (cond < 0) /* go to the left subtree */
p->left = bintree_insert(p->left, t);
else /* go to the right subtree */
p->right = bintree_insert(p->right, t);
return p;
}
/* in-order tree print */
void treeprint_inorder(struct tnode *p)
{
if (p != NULL)
{
treeprint_inorder(p->left);
printf("%4d %s\n", p->count, p->text);
treeprint_inorder(p->right);
}
}
int main(int argc, char **argv)
{
struct tnode *root = NULL;
char *tokens[] = { "Anything", "that", "can", "go", "wrong", "will",
"binary", "tress", "are", "usefull",
"dreaming", "in", "digital", "living", "in",
"binary", "talking", "in", "ip"};
int i;
for (i = 0; i < sizeof(tokens) / sizeof(char *); i++)
root = bintree_insert(root, tokens[i]);
treeprint_inorder(root);
return 0;
}
|