Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Trie

1 topic · 28 Nov 2026
1

Trie ★★☆☆☆

Data Structure

A trie (prefix tree) stores strings character by character. Insert and search take O(length of word). Used for autocomplete, spell check and prefix search.

C++
struct TrieNode {
    TrieNode *child[26] = {};
    bool isEnd = false;
};

void insert(TrieNode *root, const string &w) {
    for (char c : w) {
        int i = c - 'a';
        if (!root->child[i]) root->child[i] = new TrieNode();
        root = root->child[i];
    }
    root->isEnd = true;
}

bool search(TrieNode *root, const string &w) {
    for (char c : w) {
        root = root->child[c - 'a'];
        if (!root) return false;
    }
    return root->isEnd;
}