aboutsummaryrefslogtreecommitdiff
path: root/6.2/tree.c
diff options
context:
space:
mode:
Diffstat (limited to '6.2/tree.c')
-rw-r--r--6.2/tree.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/6.2/tree.c b/6.2/tree.c
new file mode 100644
index 0000000..5e061a4
--- /dev/null
+++ b/6.2/tree.c
@@ -0,0 +1,67 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "tree.h"
+
+struct tnode *naddtree(struct tnode *p, char *w, int bar, int prevmatch)
+{
+ int cond;
+
+ if (p == NULL) {
+ p = talloc();
+ p->word = sneed_strdup(w);
+ p->count = 1;
+ p->match = prevmatch;
+ p->left = p->right = NULL;
+ } else {
+ if ((!strncmp(p->word, w, bar) && strcmp(p->word, w)))
+ p->match = prevmatch = YES;
+
+ if ((cond = strcmp(w, p->word)) == 0) {
+ p->count++;
+ } else if (cond < 0) {
+ p->left = naddtree(p->left, w, bar, prevmatch);
+ } else if (cond > 0) {
+ p->right = naddtree(p->right, w, bar, prevmatch);
+ }
+ }
+
+ return p;
+}
+
+void ntreeprint(struct tnode *p)
+{
+ if (p != NULL) {
+ ntreeprint(p->left);
+ if (p->match)
+ printf("%4d %s\n", p->count, p->word);
+ ntreeprint(p->right);
+ }
+}
+
+void treefree(struct tnode *p) {
+ if (p != NULL) {
+ if (p->left != NULL)
+ treefree(p->left);
+ if (p->right != NULL)
+ treefree(p->right);
+ free(p->word);
+ free(p);
+ }
+}
+
+struct tnode *talloc(void)
+{
+ return (struct tnode *) malloc(sizeof(struct tnode));
+}
+
+char *sneed_strdup(char *s)
+{
+ char *p;
+
+ p = (char *) malloc(strlen(s) + 1);
+ if (p != NULL)
+ strcpy(p, s);
+
+ return p;
+}