summaryrefslogtreecommitdiffstats
path: root/trees.c
diff options
context:
space:
mode:
Diffstat (limited to 'trees.c')
-rw-r--r--trees.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/trees.c b/trees.c
new file mode 100644
index 0000000..3a5599c
--- /dev/null
+++ b/trees.c
@@ -0,0 +1,58 @@
+/* trees.c
+ *
+ * Trees
+ *
+ */
+
+#include "trees.h"
+
+/* addtree, 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 the the left subtree */
+ p->left = bintree_insert(p->left, t);
+ else
+ 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;
+}
+