How to build binary tree of words, count the words occurrences, print the words sorted (ABC...) and free the tree in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h> 

struct node 
{ 
    char *word; 
    int count; 
    struct node *left; 
    struct node *right; 
}; 

#define WORD_MAX_LEN 64
#define WORD_COUNT 7

struct node *add_to_tree(struct node *n, char *w);
void print_tree(struct node *n);
void free_tree(struct node *n);
char *my_strdup(char *s);

int main(void)
{
    struct node *root = NULL;
    char word[WORD_MAX_LEN];
    int i = 0;
    
    printf("Input Words:\n");
    while (i < WORD_COUNT)
    {
           gets(word);
           root = add_to_tree(root, word);
           i++;
    }
    printf("\nPrint The Tree Sorted:\n");
    print_tree(root);
    free_tree(root);
    
    return 0;
}
struct node *add_to_tree(struct node *n, char *w)
{
    int cmp;
    
    if (n == NULL) 
    { 
        if ( (n = (struct node *) malloc(sizeof(struct node)) ) == NULL)
        {
            printf("malloc error");
            EXIT_FAILURE;
        }
        n->word = my_strdup(w);
        n->count = 1;
        n->left = n->right = NULL;
    } 
    else if ( (cmp = strcmp(w, n->word) ) == 0)
               n->count++; 
         else if (cmp < 0) 
                  n->left = add_to_tree(n->left, w);
              else 
                  n->right = add_to_tree(n->right, w);
    return n;
}
char *my_strdup(char *w)
{
    char *p;
    
    if ( (p = (char *) malloc(sizeof(char) * (strlen(w) + 1)) ) == NULL)
    {
         printf("malloc error");
         EXIT_FAILURE;   
    }
    if (p != NULL)
        strcpy(p,  w);

    return p;
}
void print_tree(struct node *n)
{
    if (n != NULL) 
    {
        print_tree(n->left);
        printf("%s %4d\n", n->word, n->count);
        print_tree(n->right);
    }
}
void free_tree(struct node *n)
{
    if (n == NULL) 
        return;
    
    free_tree(n->left);
    free_tree(n->right);
    free(n->word);
    free(n);
}

/*
run:
 
Input Words:
www
aaa
vvv
aaa
ccccccccc
zz
yyyy

Print The Tree Sorted:
aaa    2
ccccccccc    1
vvv    1
www    1
yyyy    1
zz    1


*/

 



answered Dec 5, 2015 by avibootz
edited Apr 15, 2016 by avibootz

Related questions

1 answer 174 views
2 answers 249 views
1 answer 185 views
1 answer 130 views
130 views asked Jun 14, 2023 by avibootz
1 answer 171 views
1 answer 185 views
...