Menu
Coddy logo textTech

Trie Class

Lesson 4 of 14 in Coddy's Tries - Data Structures Series #8 course.

The Trie class itself is very thin: it owns a single field, root, which is a TrieNode. Every insert, search, and lookup starts from this root and walks down the tree one character at a time.

The constructor creates a fresh TrieNode for the root. That root has no children yet and is not marked as the end of any word, so the trie starts empty. The methods we add in the next lessons will grow children off it.

challenge icon

Challenge

Easy

Write a class Trie with a constructor that takes no input.

Initialize a single field root as a new TrieNode (using the class you wrote in the previous lesson).

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "trie.h"

int main() {
    Trie t;
    Trie_init(&t);
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "rootIsEmpty") == 0) { printf("%s\n", TrieNode_childrenCount(t.root) == 0 ? "true" : "false"); }
    }
    return 0;
}

All lessons in Tries - Data Structures Series #8