File tree 1 file changed +66
-0
lines changed
implement-trie-prefix-tree
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node {
2
+ public:
3
+ char data;
4
+ unordered_map<char ,Node*> m;
5
+ bool is_terminal;
6
+
7
+ Node (char d){
8
+ data = d;
9
+ is_terminal = false ;
10
+ }
11
+ };
12
+
13
+
14
+ class Trie {
15
+ public:
16
+ Node* root;
17
+
18
+ Trie () {
19
+ root = new Node (' \0 ' );
20
+ }
21
+
22
+ void insert (string word) {
23
+ Node* temp = root;
24
+
25
+ for (char ch: word){
26
+ if (temp->m .count (ch)==0 ){
27
+ Node* n = new Node (ch);
28
+ temp->m [ch] = n;
29
+ }
30
+ temp = temp->m [ch];
31
+ }
32
+ temp->is_terminal = true ;
33
+ }
34
+
35
+ bool search (string word) {
36
+ Node* temp = root;
37
+
38
+ for (char ch: word){
39
+ if (temp->m .count (ch)==0 ){
40
+ return false ;
41
+ }
42
+ temp = temp->m [ch];
43
+ }
44
+ return temp->is_terminal ;
45
+ }
46
+
47
+ bool startsWith (string prefix) {
48
+ Node* temp = root;
49
+
50
+ for (char ch: prefix){
51
+ if (temp->m .count (ch)==0 ){
52
+ return false ;
53
+ }
54
+ temp = temp->m [ch];
55
+ }
56
+ return true ;
57
+ }
58
+ };
59
+
60
+ /* *
61
+ * Your Trie object will be instantiated and called as such:
62
+ * Trie* obj = new Trie();
63
+ * obj->insert(word);
64
+ * bool param_2 = obj->search(word);
65
+ * bool param_3 = obj->startsWith(prefix);
66
+ */
You can’t perform that action at this time.
0 commit comments