/* 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; }