-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrieDataStructure.cpp
More file actions
72 lines (66 loc) · 1.58 KB
/
Copy pathTrieDataStructure.cpp
File metadata and controls
72 lines (66 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
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<bits/stdc++.h>
using namespace std;
class Trie {
public:
Trie* children[26];
bool isEnd;
Trie() {
for(Trie* a : this->children)
a = NULL;
isEnd = false;
}
};
void insertString(Trie* root, string s) {
Trie* temp = root;
for(char ch : s) {
int index = ch - 'a';
if(temp->children[index] == NULL) {
temp->children[index] = new Trie();
}
temp = temp->children[index];
}
temp->isEnd = true;
}
bool isLeaf(Trie* root) {
for(Trie* a : root->children) {
if(a != NULL) return false;
}
return true;
}
Trie* deleteString(Trie* root, int current_index, string s) {
if(root == NULL) return NULL;
if(current_index == s.length()) {
if(root->isEnd) {
root->isEnd = false;
}
if(isLeaf(root)) {
delete (root);
return NULL;
}
return root;
}
int index = s[current_index] - 'a';
root->children[index] = deleteString(root->children[index], current_index + 1, s);
if(isLeaf(root) && root->isEnd) {
delete (root);
root = NULL;
}
return root;
}
bool search(Trie* root, string s) {
Trie* temp = root;
for(char ch : s) {
int index = ch - 'a';
if(temp->children[index] == NULL) return false;
temp = temp->children[index];
}
return temp->isEnd;
}
int main() {
Trie* trie = new Trie();
insertString(trie, "abc");
insertString(trie, "abd");
deleteString(trie, 0, "abd");
cout << search(trie, "ab") << endl;
return 0;
}