Repository navigation
Expand file tree
/
Copy pathTrie.cpp
More file actions
96 lines (80 loc) · 1.91 KB
/
Copy pathTrie.cpp
File metadata and controls
96 lines (80 loc) · 1.91 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
#include <iostream>
#include <string>
#include <cmath>
#include "Trie.h"
using namespace std;
//constructor
Trie::Trie()
{
for(int i = 0; i < ALPHABET_SIZE; i ++)
children[i] = NULL;
isEndOfWord = false;
}
//destructor
Trie::~Trie()
{
for (int i = 0; i < ALPHABET_SIZE; i++)
delete children[i];
}
//clears all data from the trie and reallocates children so that trie can continue to be used.
void Trie::clear()
{
for (int i = 0; i < ALPHABET_SIZE; i++)
delete children[i];
for(int i = 0; i < ALPHABET_SIZE; i ++)
children[i] = NULL;
}
//checks if a word exists in the trie
bool Trie::exists(string str)
{
Trie *trieCrawler = this;
for (int i = 0; i < str.length(); i++)
{
int index = str[i] - CASE;
if (!trieCrawler->children[index])
return false;
trieCrawler = trieCrawler->children[index];
}
return (trieCrawler != NULL && trieCrawler->isEndOfWord);
}
//inserts a word into the trie
void Trie::insert(string str)
{
Trie *trieCrawler = this;
for (int i = 0; i < str.length(); i++)
{
int index = abs(str[i] - CASE);
if (!trieCrawler->children[index])
trieCrawler->children[index] = new Trie;
trieCrawler = trieCrawler->children[index];
}
trieCrawler->isEndOfWord = true;
}
//prints all contents of the trie in a list
void Trie::printTrie(deque<char> prefix)
{
if (this->isEndOfWord)
print(prefix);
for (int i = 0; i < ALPHABET_SIZE; ++i)
{
if (this->children[i])
{
char indexChar = i + 'A';
prefix.push_back(indexChar);
this->children[i]->printTrie(prefix);
prefix.pop_back();
}
}
}
//helper method for the printTrie() function
void Trie::print(deque<char> toPrint)
{
while (!toPrint.empty())
{
char f = toPrint.front();
toPrint.pop_front();
f = tolower(f);
cout << f ;
}
cout << ", ";
}