1
+ /*
2
+ Author: Aryan Yadav
3
+ Implement Trie (Prefix Tree)
4
+
5
+ Complexity: O(n)
6
+ Algorithm: NA
7
+ Difficulty: Hard
8
+ Data Structure: Trie
9
+ */
10
+
11
+ class TrieNode
12
+ {
13
+ public:
14
+ // Initialize your data structure here.
15
+ TrieNode ()
16
+ {
17
+ count = 0 ;
18
+ for (int i = 0 ; i < 26 ; ++i)
19
+ {
20
+ next[i] = NULL ;
21
+ }
22
+ }
23
+
24
+ int count;
25
+ TrieNode *next[26 ];
26
+ };
27
+
28
+ class Trie
29
+ {
30
+ public:
31
+ Trie ()
32
+ {
33
+ root = new TrieNode ();
34
+ }
35
+
36
+ ~Trie ()
37
+ {
38
+ this ->deleteNodes (root);
39
+ }
40
+
41
+ // Inserts a word into the trie.
42
+ void insert (string key)
43
+ {
44
+ TrieNode *cur = this ->root ;
45
+ for (size_t i = 0 ; i < key.size (); ++i)
46
+ {
47
+ if (cur->next [key[i] - ' a' ] == NULL )
48
+ {
49
+ cur->next [key[i] - ' a' ] = new TrieNode ();
50
+ }
51
+ cur = cur->next [key[i] - ' a' ];
52
+ }
53
+ ++cur->count ;
54
+ }
55
+
56
+ // Returns if the word is in the trie.
57
+ bool search (string key)
58
+ {
59
+ return getTargetCount (key) > 0 ;
60
+ }
61
+
62
+ // Returns if there is any word in the trie
63
+ // that starts with the given prefix.
64
+ bool startsWith (string prefix)
65
+ {
66
+ return this ->getTargetCount (prefix) != -1 ;
67
+ }
68
+
69
+ void deleteNodes (TrieNode *node)
70
+ {
71
+ if (node == NULL )
72
+ {
73
+ return ;
74
+ }
75
+
76
+ for (size_t i = 0 ; i < 26 ; ++i)
77
+ {
78
+ this ->deleteNodes (node->next [i]);
79
+ }
80
+
81
+ delete node;
82
+ }
83
+
84
+ private:
85
+ int getTargetCount (string key)
86
+ {
87
+ TrieNode *cur = this ->root ;
88
+ for (size_t i = 0 ; i < key.size (); ++i)
89
+ {
90
+ if (cur->next [key[i] - ' a' ] == NULL )
91
+ {
92
+ return -1 ;
93
+ }
94
+ cur = cur->next [key[i] - ' a' ];
95
+ }
96
+ return cur->count ;
97
+ }
98
+ TrieNode *root;
99
+ };
100
+
101
+ /* *
102
+ * Your Trie object will be instantiated and called as such:
103
+ * Trie* obj = new Trie();
104
+ * obj->insert(word);
105
+ * bool param_2 = obj->search(word);
106
+ * bool param_3 = obj->startsWith(prefix);
107
+ */
0 commit comments