Skip to content

Commit f3f1536

Browse files
authored
Merge pull request #133 from shubhamguptaji/TrieTree
Trie Tree
2 parents aead0ba + 975cefb commit f3f1536

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

Datastructures/TrieTree.cpp

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#include<iostream>
2+
#include<string.h>
3+
#include<stdbool.h>
4+
using namespace std;
5+
// structure definition
6+
typedef struct trie
7+
{
8+
struct trie *arr[26];
9+
bool isEndofWord;
10+
} trie;
11+
// create a new node for trie
12+
trie *createNode()
13+
{
14+
trie *nn = new trie();
15+
for (int i = 0; i < 26; i++)
16+
nn->arr[i] = NULL;
17+
nn->isEndofWord = false;
18+
return nn;
19+
}
20+
21+
// insert string into the trie
22+
void insert(trie *root, char* str)
23+
{
24+
for (int i = 0; i < strlen(str); i++)
25+
{
26+
int j = str[i] - 'a';
27+
if (root->arr[j])
28+
{
29+
root = root->arr[j];
30+
}
31+
else
32+
{
33+
root->arr[j] = createNode();
34+
root = root->arr[j];
35+
}
36+
}
37+
root->isEndofWord = true;
38+
}
39+
40+
// search a string exists inside the trie
41+
bool search(trie *root, char* str, int index)
42+
{
43+
if (index == strlen(str))
44+
{
45+
if (!root->isEndofWord)
46+
return false;
47+
return true;
48+
}
49+
int j = str[index] - 'a';
50+
if (!root->arr[j])
51+
return false;
52+
return search(root->arr[j], str, index + 1);
53+
}
54+
/* removes the string if it is not a prefix of any other
55+
string, if it is then just sets the endofword to false, else
56+
removes the given string*/
57+
bool deleteString (trie *root, char* str, int index)
58+
{
59+
if (index == strlen(str))
60+
{
61+
if (!root->isEndofWord)
62+
return false;
63+
root->isEndofWord = false;
64+
for (int i = 0; i < 26; i++)
65+
return false;
66+
return true;
67+
}
68+
int j = str[index] - 'a';
69+
if (!root->arr[j])
70+
return false;
71+
bool var = deleteString (root, str, index + 1);
72+
if (var)
73+
{
74+
root->arr[j] = NULL;
75+
if (root->isEndofWord)
76+
return false;
77+
else
78+
{
79+
int i;
80+
for (i = 0; i < 26; i++)
81+
if (root->arr[i])
82+
return false;
83+
return true;
84+
}
85+
}
86+
}
87+
88+
int main()
89+
{
90+
trie *root = createNode();
91+
insert(root, "hello");
92+
insert(root, "world");
93+
int a = search(root, "hello", 0);
94+
int b = search(root, "word", 0);
95+
printf("%d %d ", a, b);
96+
return 0;
97+
}

0 commit comments

Comments
 (0)