Link to the problem

The problem is here: https://leetcode-cn.com/problems/implement-trie-prefix-tree/

Trie

A trie (sounds like ‘try’), also called digital tree or prefix tree, is a type of multi-way search tree (多路搜索树).

Trie can be used in tasks like auto-complete or spell-checking.

It is used to store and search strings efficiently. An intuitive design of a trie is like this:

wordtrie.jpg

The root node is actually a dummy node. The boolean value of a node is indicating whether that node is a termination or not.

For example, an is a word in the trie while na is not.

Simple Implementation

  1. class Trie {
  2. private:
  3. struct TrieNode {
  4. vector<TrieNode *> child_;
  5. bool terminated_;
  6. TrieNode() : child_(26, nullptr), terminated_(false) { }
  7. };
  8. TrieNode root_;
  9. public:
  10. /** Initialize your data structure here. */
  11. Trie() {}
  12. /** Inserts a word into the trie. */
  13. void insert(string word) {
  14. auto node = &root_;
  15. for (char c : word) {
  16. auto idx = c - 'a';
  17. if (!node->child_[idx]) {
  18. node->child_[idx] = new TrieNode();
  19. }
  20. node = node->child_[idx];
  21. }
  22. node->terminated_ = true;
  23. }
  24. /** Returns if the word is in the trie. */
  25. bool search(string word) {
  26. auto node = &root_;
  27. for (char c : word) {
  28. auto idx = c - 'a';
  29. if (!node->child_[idx]) {
  30. return false;
  31. }
  32. node = node->child_[idx];
  33. }
  34. return node->terminated_;
  35. }
  36. /** Returns if there is any word in the trie that starts with the given prefix. */
  37. bool startsWith(string prefix) {
  38. auto node = &root_;
  39. for (char c : prefix) {
  40. auto idx = c - 'a';
  41. if (!node->child_[idx]) {
  42. return false;
  43. }
  44. node = node->child_[idx];
  45. }
  46. return true;
  47. }
  48. };
  49. /**
  50. * Your Trie object will be instantiated and called as such:
  51. * Trie* obj = new Trie();
  52. * obj->insert(word);
  53. * bool param_2 = obj->search(word);
  54. * bool param_3 = obj->startsWith(prefix);
  55. */

Possible Improvements

May use map instead of vector to save memory usage.