forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement-Trie.cpp
90 lines (87 loc) · 1.79 KB
/
Implement-Trie.cpp
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 <bits/stdc++.h>
using namespace std;
class trienode
{
public:
char data;
trienode *children[26];
bool isterminal;
trienode(char ch)
{
data = ch;
for (int i = 0; i < 26; i++)
{
children[i] = NULL;
}
isterminal = false;
}
};
class trie
{
public:
trienode *root;
trie()
{
root = new trienode('\0');
}
void insertutil(trienode *root, string word)
{
// base case
if (word.length() == 0)
{
root->isterminal = true;
return;
}
trienode *child;
int index = word[0] - 'a';
if (root->children[index] != NULL)
{
// character is present
child = root->children[index];
}
else
{
child = new trienode(word[0]);
root->children[index] = child;
}
insertutil(child, word.substr(1));
}
void insertword(string word)
{
insertutil(root, word);
}
bool searchutil(trienode *root, string word)
{
// base case
if (word.length() == 0)
{
return root->isterminal;
}
trienode *child;
int index = word[0] - 'a';
if (root->children[index] != NULL)
{
child = root->children[index];
}
else
{
return false;
}
return searchutil(child, word.substr(1));
}
bool search(string word)
{
return searchutil(root, word);
}
};
int main()
{
trie *t = new trie;
t->insertword("abcd");
t->insertword("sampad");
t->insertword("saikat");
cout << t->search("abcdk") << endl;
cout << t->search("sampad") << endl;
cout << t->search("saikat") << endl;
return 0;
}