-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
102 lines (81 loc) · 2.18 KB
/
Copy pathTrie.cpp
File metadata and controls
102 lines (81 loc) · 2.18 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
100
101
102
#include "Trie.h"
// Default Constructor
Trie::Trie()
{
// create a new node for root
root = new TrieNode();
}
// Destructor
Trie::~Trie() {
// deleteTrie(root);
}
// Insert Function
void Trie::insert(const string &word)
{
// Set a pointer for root
TrieNode *current = root;
// Iterate through each alphabet
for (char c : word)
{
// If the word already exists in the trie
if (current->children.find(c) == current->children.end())
{
// If not then insert the character manually
current->children[c] = new TrieNode();
}
// Move pointer to the next child
current = current->children[c];
}
// After inserting the entire word, mark the end of the word
current->isEndOfWord = true;
}
// Search Function
bool Trie::search(const string &word) const
{
//Set a pointer for root
TrieNode *current = root;
//Iterate through
for (char c : word)
{
//If the current character is empty
if (current->children.find(c) == current->children.end())
{
return false;
}
//Move to pointer to the next character
current = current->children[c];
}
//Return true if end of word is reached
return current->isEndOfWord;
}
//Function to check the starting prefix
bool Trie::startsWith(const string& prefix)
{
//Start from root
TrieNode* current = root;
//Iterate through each character
for(char c: prefix)
{
//If current character is null
if(current->children.find(c) == current->children.end())
{
//Return false if element not found
return false;
}
//Move to child
current = current->children[c];
}
//return true if successfully iterated and no null node found
return true;
}
//Recursive Function to delete the trie
void Trie::deleteTrie(TrieNode* node)
{
for(auto& c : node->children)
{
//keep moving to child
deleteTrie(c.second);
}
//deleting current child
delete node;
}