Skip to content

Commit cbef527

Browse files
Trie Tree
1 parent aead0ba commit cbef527

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

Datastructures/TrieTree.cpp

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#include<iostream>
2+
#include<string.h>
3+
#include<stdbool.h>
4+
using namespace std;
5+
6+
typedef struct trie
7+
{
8+
struct trie *arr[26];
9+
bool isEndofWord;
10+
} trie;
11+
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+
void insert(trie *root, char* str)
22+
{
23+
for (int i = 0; i < strlen(str); i++)
24+
{
25+
int j = str[i] - 'a';
26+
if (root->arr[j])
27+
{
28+
root = root->arr[j];
29+
}
30+
else
31+
{
32+
root->arr[j] = createNode();
33+
root = root->arr[j];
34+
}
35+
}
36+
root->isEndofWord = true;
37+
}
38+
39+
bool search(trie *root, char* str, int index)
40+
{
41+
if (index == strlen(str))
42+
{
43+
if (!root->isEndofWord)
44+
return false;
45+
return true;
46+
}
47+
int j = str[index] - 'a';
48+
if (!root->arr[j])
49+
return false;
50+
return search(root->arr[j], str, index + 1);
51+
}
52+
53+
bool deleteString (trie *root, char* str, int index)
54+
{
55+
if (index == strlen(str))
56+
{
57+
if (!root->isEndofWord)
58+
return false;
59+
root->isEndofWord = false;
60+
for (int i = 0; i < 26; i++)
61+
return false;
62+
return true;
63+
}
64+
int j = str[index] - 'a';
65+
if (!root->arr[j])
66+
return false;
67+
bool var = deleteString (root, str, index + 1);
68+
if (var)
69+
{
70+
root->arr[j] = NULL;
71+
if (root->isEndofWord)
72+
return false;
73+
else
74+
{
75+
int i;
76+
for (i = 0; i < 26; i++)
77+
if (root->arr[i])
78+
return false;
79+
return true;
80+
}
81+
}
82+
}
83+
84+
int main()
85+
{
86+
trie *root = createNode();
87+
insert(root, "hello");
88+
insert(root, "world");
89+
int a = search(root, "hello", 0);
90+
int b = search(root, "word", 0);
91+
printf("%d %d ", a, b);
92+
return 0;
93+
}

0 commit comments

Comments
 (0)