-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTRIE.cpp
107 lines (91 loc) · 2.05 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include<iostream>
#include<cstdlib>
#include<vector>
#include<stack>
using namespace std;
struct Node
{
Node* parent=NULL;
Node* children[26];
int occurances=0;
};
void Insert(Node* TrieRoot,string word)
{
Node* root=TrieRoot;
for(int i=0;i<word.length();++i)
{
if(root->children[word[i]-'a']!=NULL)
{
root=root->children[word[i]-'a'];
continue;
}
Node* temp=new Node();
temp->parent=root;
root->children[word[i]-'a'] = temp;
root=temp;
}
root->occurances += 1;
}
int Search(Node* TrieRoot,string word)
{
for(int i=0;i<word.length();++i)
{
if(TrieRoot->children[word[i]-'a']==NULL)
return 0;
TrieRoot=TrieRoot->children[word[i]-'a'];
}
if(TrieRoot->occurances>0)
return TrieRoot->occurances;
return 0; // return 1;
}
void Delete(Node* TrieNode,string word)
{
Node* root=TrieNode;
vector< Node* > vec;
for(int i=0;i<word.length();++i)
{
if(root->children[word[i]-'a']==NULL)
{
cout<<"ERROR 404, \""<<word<<"\" Not Found\n";
return;
}
root=root->children[word[i]-'a'];
vec.push_back(root);
}
root->occurances -=1;
while(!vec.empty())
{
Node* tmp=(vec.back());
vec.pop_back();
if(tmp->occurances!=0)
return;
free(tmp);
}
vec.clear();
}
int main()
{
Node* TrieRoot=new Node();
Insert(TrieRoot,"the");
Insert(TrieRoot,"this");
Insert(TrieRoot,"facade");
Insert(TrieRoot,"facebook");
Insert(TrieRoot,"this");
int t=0;
t = Search(TrieRoot,"this");
t ? cout<<t<<"\n" : cout<<"Not Found\n";
t = Search(TrieRoot,"facebook");
t ? cout<<t<<"\n" : cout<<"Not Found\n";
/* t = Search(TrieRoot,"this");
t ? cout<<"Found\n" : cout<<"Not Found\n";
t = Search(TrieRoot,"facebook");
t ? cout<<"Found\n" : cout<<"Not Found\n"; */
Delete(TrieRoot,"facebook");
t = Search(TrieRoot,"facebook");
t ? cout<<t<<"\n" : cout<<"Not Found\n";
Delete(TrieRoot,"poop");
Delete(TrieRoot,"this");
t = Search(TrieRoot,"this");
t ? cout<<t<<"\n" : cout<<"Not Found\n";
return 0;
}