This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.cpp
152 lines (120 loc) · 2.33 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include <iostream>
using namespace std;
struct node
{
node *number[10];
bool isLeaf;
} *root = NULL;
node *getNode()
{
node *temp = new node();
temp -> isLeaf = false;
for(int i = 0; i < 10; i++)
{
temp -> number[i] = NULL;
}
return temp;
}
void insert(int a)
{
if(root == NULL)
root = getNode();
node *current = root;
while(a != 0)
{
if(current -> number[a % 10] == NULL)
{
node *new_node = getNode();
current -> number[a % 10] = new_node;
current = new_node;
}
else
current = current -> number[a % 10];
a /= 10;
}
current -> isLeaf = true;
}
void search(int value)
{
if(root == NULL)
cout << "There is no word in Trie" << endl;
node *current = root;
int a = value;
while(a != 0)
{
if(current -> number[a % 10] == NULL)
{
break;
}
else
current = current -> number[a % 10];
a /= 10;
}
if(a == 0 && current -> isLeaf == true)
cout << value << " Found" << endl;
else
cout << value << " Not Present" << endl;
}
bool isFreeNode(node *root)
{
for(int i = 0; i < 10; i++)
{
if(root -> number[i] != NULL)
return false;
}
return true;
}
bool removeNumber(node *root, int a)
{
if(root)
{
if(a == 0)
{
if(root -> isLeaf)
{
root -> isLeaf = false;
if(isFreeNode(root))
return true;
}
return false;
}
else
{
if(removeNumber(root -> number[a % 10], a / 10))
{
delete root -> number[a % 10];
root -> number[a % 10] = NULL;
return (!root -> isLeaf && isFreeNode(root));
}
}
}
return false;
}
void remove(int a)
{
if(a != 0 && root != NULL)
removeNumber(root, a);
}
int main()
{
int a = 99, b = 9999, c = 9987, d = 8687, e = 5499;
insert(a);
insert(b);
insert(c);
insert(d);
insert(e);
search(a);
search(b);
search(e);
search(7676);
remove(a);
search(a);
return 0;
}
/* Output
99 Found
9999 Found
5499 Found
7676 Not Present
99 Not Present
*/