forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie_tree.cpp
More file actions
90 lines (83 loc) · 2.11 KB
/
trie_tree.cpp
File metadata and controls
90 lines (83 loc) · 2.11 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdbool.h>
#include <iostream>
#include <string>
// structure definition
typedef struct trie {
struct trie * arr[26];
bool isEndofWord;
} trie;
// create a new node for trie
trie * createNode() {
trie * nn = new trie();
for (int i = 0; i < 26; i++)
nn -> arr[i] = NULL;
nn -> isEndofWord = false;
return nn;
}
// insert string into the trie
void insert(trie * root, std::string str) {
for (int i = 0; i < str.length(); i++) {
int j = str[i] - 'a';
if (root -> arr[j]) {
root = root -> arr[j];
} else {
root -> arr[j] = createNode();
root = root -> arr[j];
}
}
root -> isEndofWord = true;
}
// search a string exists inside the trie
bool search(trie * root, std::string str, int index) {
if (index == str.length()) {
if (!root -> isEndofWord)
return false;
return true;
}
int j = str[index] - 'a';
if (!root -> arr[j])
return false;
return search(root -> arr[j], str, index + 1);
}
/*
removes the string if it is not a prefix of any other
string, if it is then just sets the endofword to false, else
removes the given string
*/
bool deleteString(trie * root, std::string str, int index) {
if (index == str.length()) {
if (!root -> isEndofWord)
return false;
root -> isEndofWord = false;
for (int i = 0; i < 26; i++)
return false;
return true;
}
int j = str[index] - 'a';
if (!root -> arr[j])
return false;
bool
var = deleteString(root, str, index + 1);
if (var) {
root -> arr[j] = NULL;
if (root -> isEndofWord) {
return false;
} else {
int i;
for (i = 0; i < 26; i++)
if (root -> arr[i])
return false;
return true;
}
}
}
int main() {
trie * root = createNode();
insert(root, "hello");
insert(root, "world");
int a = search(root, "hello", 0);
int b = search(root, "word", 0);
printf("%d %d ", a, b);
return 0;
}