-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cpp
86 lines (81 loc) · 1.62 KB
/
trie.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 <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <new>
using namespace std;
class trieNode{
public:
bool end;
char ch;
int prefixes;
int words;
trieNode *children[150];
trieNode(char val){
this->end = false;
this->ch = val;
for(int i = 97; i <= 122 ; i++){
this->children[i] = NULL;
}
this->prefixes = 0;
this->words = 0;
}
};
void addWord(trieNode *node , string word){
if(word.empty()){
node->words = node->words + 1;
node->end = true;
}
else{
node->prefixes = node->prefixes + 1;
char tmp = *(word.begin());
//cout <<"char = "<<tmp<<endl;
if(node->children[tmp] == NULL){
trieNode *newnode = new trieNode(tmp);
node->children[tmp] = newnode;
}
// cout<<node->children[tmp]->ch;
word.erase(word.begin());
addWord(node->children[tmp] , word);
}
}
int countWords(trieNode *node, string word){
char tmp = *(word.begin());
if (word.empty()){
return node->words;
}
else if (node->children[tmp] == NULL){
return 0;
}
else{
word.erase(word.begin());
return countWords(node->children[tmp] , word);
}
}
void printIt(trieNode *node, string pre){
if(node->end){
cout<<pre<<endl;
}
else
{
for(int i = 97 ; i <= 122 ; i++){
if(node->children[i] != NULL){
string tmp = pre + node->children[i]->ch;
printIt(node->children[i] , tmp);
}
}
}
}
int main()
{
string pre = "";
trieNode *root = new trieNode(' ');
//root->end = true;
addWord(root, "akshit");
addWord(root, "akshay");
//cout<<"first = "<<(root->children['a']->prefixes);
addWord(root,"aks");
cout<<"word = "<<countWords(root,"akshay");
printIt(root,pre);
return 0;
}