-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement Trie (Prefix Tree).cpp
More file actions
59 lines (56 loc) · 1.58 KB
/
Copy pathImplement Trie (Prefix Tree).cpp
File metadata and controls
59 lines (56 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class TrieNode {
public:
char c;
vector<TrieNode*> child;
bool isTerminal;
TrieNode() {
child.resize(26, nullptr);
isTerminal = false;
}
TrieNode(char c) {
this->c = c;
child.resize(26, nullptr);
isTerminal = false;
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void insertUtil(TrieNode* root, string& word, int i){
if(i >= word.length()){
root->isTerminal = true;
return;
}
if(!root->child[word[i] - 'a']) root->child[word[i] - 'a'] = new TrieNode(word[i]);
insertUtil(root->child[word[i] - 'a'], word, i+1);
}
void insert(string word) {
insertUtil(root, word, 0);
}
bool searchUtil(TrieNode* root, string& word, int i){
if(i >= word.length()) return root->isTerminal;
if(!root->child[word[i] - 'a']) return false;
return searchUtil(root->child[word[i] - 'a'], word, i+1);
}
bool search(string word) {
return searchUtil(root, word, 0);
}
bool searchWithUtil(TrieNode* root, string& word, int i){
if(i >= word.length()) return true;
if(!root->child[word[i] - 'a']) return false;
return searchWithUtil(root->child[word[i] - 'a'], word, i+1);
}
bool startsWith(string prefix) {
return searchWithUtil(root, prefix, 0);
}
};
/**
* 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);
*/