title: counting occurrences of word in binary search tree
body: <p>I'm working on creating a function word_count that counts the number of occurrences of the given word in a binary search. I'm having some trouble with how the logic would work, I'm stuck on the initial part. There's another function I created word_observe, that checks if a word is in the tree if it is not it adds it in and sets the count to one. If it is it increments count every time it comes across it. That could possibly be useful to understand the full program.</p>
  <pre><code>typedef struct tnode {
    char *word;
    int count;
    struct tnode *left;
    struct tnode *right;
  } tnode;
  
  tnode *word_observe(char *word, tnode *node) {
  
          if (node != NULL) {
                  if (strcmp(node-&gt;word, word) == 0) {
                          node-&gt;count++;
                          return node;
                  } else if (strcmp(node-&gt;word, word) &lt; 0) {
                          node-&gt;left = word_observe(word, node-&gt;left);
                  } else {
                          node-&gt;right = word_observe(word, node-&gt;right);
                  }
          } else {
                  tnode *newnode = (tnode*)malloc(sizeof(tnode));
                  newnode-&gt;word = strdup(word);
                  newnode-&gt;count = 1;
                  newnode-&gt;left = NULL;
                  newnode-&gt;right = NULL;
                  node = newnode;
          }
    return node;
  }
  
  
  int word_count(char *word, tnode *node) {
          if (node != NULL) {
                  if (strcmp(node-&gt;word, word) == 0) {
                          return node-&gt;count;
                  } else if (strcmp(word, node-&gt;word) &lt; 0) {
                          word_count(word, node-&gt;left);
                  } else {
                          word_count(word, node-&gt;right);
                  }
          }
          return -1;
  }
  
  int main(void) {
    tnode *counts = NULL;
  
    counts = word_observe(&quot;dog&quot;, counts);
    counts = word_observe(&quot;dog&quot;, counts);
  
    counts = word_observe(&quot;apple&quot;, counts);
    counts = word_observe(&quot;hello&quot;, counts);
    counts = word_observe(&quot;pineapple&quot;, counts);
    counts = word_observe(&quot;pineapple&quot;, counts);
    counts = word_observe(&quot;pineapple&quot;, counts);
  
    counts = word_observe(&quot;zebra&quot;, counts);
    counts = word_observe(&quot;zebra&quot;, counts);
    counts = word_observe(&quot;zebra&quot;, counts);
    counts = word_observe(&quot;zebra&quot;, counts);
  
    printf(&quot;apple: %d\n&quot;, word_count(&quot;apple&quot;, counts));
    printf(&quot;dog: %d\n&quot;, word_count(&quot;dog&quot;, counts));
    printf(&quot;pineapple: %d\n&quot;, word_count(&quot;pineapple&quot;, counts));
    printf(&quot;zebra: %d\n&quot;, word_count(&quot;zebra&quot;, counts));
  
    return 0;
  }
  
  </code></pre>