-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
99 lines (91 loc) · 2.15 KB
/
Trie.cpp
File metadata and controls
99 lines (91 loc) · 2.15 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
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
using namespace std;
class TreeNode
{
public:
char data;
TreeNode *children[26];
bool isTerminal;
TreeNode(char ch)
{
data = ch;
for (int i = 0; i < 26; i++)
{
children[i] = nullptr;
}
isTerminal = false;
}
};
class Trie
{
public:
TreeNode *root;
Trie()
{
root = new TreeNode('\n');
}
void insertWord(TreeNode *root, string word)
{
// using recursion base case ;
if (word.length() == 0)
{
root->isTerminal = true;
return;
}
// taking every word in small latter ;
int index = word[0] - 'a';
TreeNode *child;
// there are two case to insert word into the trie 1) word is present 2) word is not present ;
// first if the word is peresent into the trie
if (root->children[index] != NULL)
{
child = root->children[index];
}
else // word is not present into the trie so we have to insert;
{
child = new TreeNode(word[0]);
root->children[index] = child;
}
// now further word will done by recursion
insertWord(child, word.substr(1));
}
// insert word into the trie;
void insert(string word)
{
insertWord(root, word);
return;
}
bool searchword(TreeNode *root, string word)
{
if (word.length() == 0)
{
return root->isTerminal;
}
int index = word[0] - 'a';
TreeNode *child;
if (root->children[index] != NULL)
{
child = root->children[index];
}
else
{ // not present;
return false;
}
return searchword(child, word.substr(1)); // recursive call to further search;
}
bool ssearch(string word)
{
return searchword(root, word);
}
};
int main()
{
Trie *t = new Trie();
// constrain here every word shoud be in cps letter ;
t->insert("raja");
if (t->ssearch("raja"))
cout << "found" << endl;
else
cout << "not found " << endl;
return 0;
}