File tree 1 file changed +67
-0
lines changed
implement-trie-prefix-tree
1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrieNode {
2
+ public:
3
+ TrieNode* children[26 ];
4
+ bool isEnd;
5
+
6
+ TrieNode () {
7
+ isEnd = false ;
8
+
9
+ for (int i = 0 ; i < 26 ; i++)
10
+ children[i] = nullptr ;
11
+ }
12
+ };
13
+
14
+ class Trie {
15
+ public:
16
+ TrieNode* root;
17
+
18
+ Trie () {
19
+ root = new TrieNode ();
20
+ }
21
+
22
+ void insert (string word) {
23
+ TrieNode* node = root;
24
+
25
+ for (char ch : word){
26
+ int index = ch - ' a' ;
27
+
28
+ if (node->children [index ] == nullptr ){
29
+ node->children [index ] = new TrieNode ();
30
+ }
31
+
32
+ node = node->children [index ];
33
+ }
34
+
35
+ node->isEnd = true ;
36
+ }
37
+
38
+ bool search (string word) {
39
+ TrieNode* node = root;
40
+
41
+ for (char ch : word){
42
+ int index = ch - ' a' ;
43
+
44
+ if (node->children [index ] == nullptr )
45
+ return false ;
46
+
47
+ node = node->children [index ];
48
+ }
49
+
50
+ return node->isEnd ;
51
+ }
52
+
53
+ bool startsWith (string prefix) {
54
+ TrieNode* node = root;
55
+
56
+ for (char ch : prefix){
57
+ int index = ch - ' a' ;
58
+
59
+ if (node->children [index ] == nullptr )
60
+ return false ;
61
+
62
+ node = node->children [index ];
63
+ }
64
+
65
+ return true ;
66
+ }
67
+ };
You can’t perform that action at this time.
0 commit comments