Skip to content

Trie Tree #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 11, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions Datastructures/TrieTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#include<iostream>
#include<string.h>
#include<stdbool.h>
using namespace std;
// structure definition
typedef struct trie
{
struct trie *arr[26];
bool isEndofWord;
} trie;
// create a new node for trie
trie *createNode()
{
trie *nn = new trie();
for (int i = 0; i < 26; i++)
nn->arr[i] = NULL;
nn->isEndofWord = false;
return nn;
}

// insert string into the trie
void insert(trie *root, char* str)
{
for (int i = 0; i < strlen(str); i++)
{
int j = str[i] - 'a';
if (root->arr[j])
{
root = root->arr[j];
}
else
{
root->arr[j] = createNode();
root = root->arr[j];
}
}
root->isEndofWord = true;
}

// search a string exists inside the trie
bool search(trie *root, char* str, int index)
{
if (index == strlen(str))
{
if (!root->isEndofWord)
return false;
return true;
}
int j = str[index] - 'a';
if (!root->arr[j])
return false;
return search(root->arr[j], str, index + 1);
}
/* removes the string if it is not a prefix of any other
string, if it is then just sets the endofword to false, else
removes the given string*/
bool deleteString (trie *root, char* str, int index)
{
if (index == strlen(str))
{
if (!root->isEndofWord)
return false;
root->isEndofWord = false;
for (int i = 0; i < 26; i++)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ms10398 Can you please explain about these two lines?

for (int i = 0; i < 26; i++)
    return false;

As I understand, this loop will execute exactly once and will always return false and never true.
Can you fix that? If you can document the code, that would be much helpful. Thanks.

return false;
return true;
}
int j = str[index] - 'a';
if (!root->arr[j])
return false;
bool var = deleteString (root, str, index + 1);
if (var)
{
root->arr[j] = NULL;
if (root->isEndofWord)
return false;
else
{
int i;
for (i = 0; i < 26; i++)
if (root->arr[i])
return false;
return true;
}
}
}

int main()
{
trie *root = createNode();
insert(root, "hello");
insert(root, "world");
int a = search(root, "hello", 0);
int b = search(root, "word", 0);
printf("%d %d ", a, b);
return 0;
}