-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrieTree.cpp
executable file
·86 lines (84 loc) · 1.51 KB
/
TrieTree.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
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
const int alphabetSize = 26;
class Node {
public:
Node() {
count = 0;
child = new Node* [alphabetSize];
for (int i = 0; i < alphabetSize; ++i) {
child[i] = NULL;
}
}
int getCount() {
return count;
;
}
void setCount(int newNumber) {
count = newNumber;
;
}
Node* getChild(int index) {
return child[index];
;
}
void setChild(Node* newChild, int index) {
child[index] = newChild;
return;
}
private:
Node** child;
char value;
int count;
};
class TrieTree {
public:
TrieTree() {
root = NULL;
}
void add(std::string word) {
Node* curr = root;
for (int i = 0; i < (int)word.size(); ++i) {
if (curr->getChild(word[i]-'a') == NULL) {
Node* tmp = new Node;
curr->setChild(tmp, int(word[i]-'a'));
}
curr = curr->getChild(word[i]-'a');
}
curr->setCount(curr->getCount() + 1);
return;
}
void del(std::string word) {
Node* curr = root;
for (int i = 0; i < word.size(); ++i) {
if (curr->getChild(word[i]-'a') == NULL) {
return;
}
curr = curr->getChild(word[i]-'a');
}
curr->setCount(std::max(curr->getCount()-1, 0));
return;
}
int count(std::string word) {
Node* curr = root;
for (int i = 0; i < word.size(); ++i) {
if (curr->getChild(word[i]-'a') == NULL) {
return;
}
curr = curr->getChild(word[i]-'a');
}
return curr->getCount();
}
Node* getRoot() {
return root;
;
}
bool isEmpty() {
return ((root==NULL)?true:false);
;
}
private:
Node* root;
};