-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie_Node.cpp
More file actions
76 lines (59 loc) · 1.25 KB
/
Trie_Node.cpp
File metadata and controls
76 lines (59 loc) · 1.25 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
#include "Trie_Node.h"
Trie_Node::Trie_Node(char a_c)
: m_Value(a_c), m_EOW(false)
{
for(int i = 0; i < 26; i++)
{
m_Children[i] = 0;
}
}
Trie_Node::~Trie_Node(void)
{
for(int i = 0; i < 26; i++)
{
if (m_Children[i] != 0)
delete m_Children[i];
m_Children[i] = 0;
}
}
// Returns the child of this with value char c
Trie_Node* Trie_Node::SubNode(char c)
{
return m_Children[c - 'a'];
}
// Inserts the word in Trie
// O(strlen(word)) :: O(1)
void Trie_Node::Insert(const std::string &ar_Word)
{
Trie_Node* current = this;
for(std::size_t i = 0; i < ar_Word.length(); i++)
{
char ch = ar_Word[i];
Trie_Node* child = current->SubNode(ch);
if(child == 0)
{
child = new Trie_Node(ch);
current->m_Children[ch - 'a'] = child;
}
current = child;
}
// current right now points to the last letter of word in trie
current->m_EOW = true;
}
// Searches for Word/Pattern in Trie
// O(strlen(word) ) :: O(1)
bool Trie_Node::Search(const std::string &ar_Word, bool patternOnly)
{
Trie_Node* current = this;
for(std::size_t i = 0; i < ar_Word.length(); i++)
{
char ch = ar_Word[i];
Trie_Node* child = current->SubNode(ch);
if(child == 0)
return false;
current = child;
}
if(patternOnly)
return true;
return current->m_EOW;
}