Search code examples
ctrie

Creating new nodes in a trie data structure in C


I'm trying to implement a trie data structure in C and having trouble figuring out how to dynamically name new nodes that are added to the dictionary. See the last few lines of my add method where I try to create a new node and try to point to it.

bool add(char *word, node tree)
{
    // Creates a variable to store the current char in the string
    char currChar = word[0];
    // Converts the current char to an index #
    int currCharIndex = ((int) toupper(currChar)) - 65;

    // Checks if we've reached the end of the word
    if (currChar == '\0')
    {
        // Sets current node word to true
        tree.word = true;
    }
    // Checks if next letter in word is not NULL
    else if (tree.children[currCharIndex] != NULL)
    {
        // Follows the pointer
        return add(&word[1], *tree.children[currCharIndex],);
    }
    else
    {
        //Creates a new node
        node; // TODO: name node
        // Points the current node to the new node
        tree.children[currCharIndex] = &// TODO: new node name
        return add(&word[1], *tree.children[currCharIndex]);
    }
}

Here is how I define node:

typedef struct node
{
    bool word;
    struct node *children[26];
}
node;

bool search(char *word, node tree);
bool add(char *word, node tree);

int main(void)
{
    node dictionary;
}

Solution

  • In the prototype of add that you have, you pass tree by value and so whatever changes done to tree inside add will get lost after the function returns. You first need to change prototype of add to take pointer as below.

    bool add(char *word, node * tree)
    

    Then you can allocate memory to add the node as below

    ...
    else
    {
        //Creates a new node
        node * newnode;
        newnode = malloc(sizeof(node));
        //TODO Initialize newnode i.e. set all children to NULL.
        tree->children[currCharIndex] = newnode;
        return add(&word[1], tree->children[currCharIndex]);
    }
    

    Also fix other parts of the code to pass pointer instead of value.

    ...
    else if (tree->children[currCharIndex] != NULL)
    {
        return add(&word[1], tree->children[currCharIndex]);
    }