# [208\. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) :::spoiler Solution ```cpp= class TrieNode { public: TrieNode* child[26]; bool isWord = false; TrieNode() { for (int i = 0; i < 26; ++i) { child[i] = nullptr; } } }; class Trie { private: TrieNode* root; public: Trie() { root = new TrieNode(); } void insert(string word) { TrieNode* node = root; for (auto w : word) { if (!node->child[w - 'a']) { node->child[w - 'a'] = new TrieNode(); } node = node->child[w - 'a']; } node->isWord = true; } bool search(string word) { TrieNode* node = root; for (auto w : word) { if (!node->child[w - 'a']) return false; node = node->child[w - 'a']; } return node->isWord; } bool startsWith(string prefix) { TrieNode* node = root; for (auto p : prefix) { if (!node->child[p - 'a']) return false; node = node->child[p - 'a']; } return true; } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */ ``` - T: $O(N)$ - S: $O(N)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up