Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

feat: add Trie Data Structure using Java #123

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
70 changes: 70 additions & 0 deletions Data Structures/Trie/Trie.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
public class Trie {

// Alphabet size (# of symbols)
static final int ALPHABET_SIZE = 26;

// trie node
static class TrieNode
{
TrieNode[] children = new TrieNode[ALPHABET_SIZE];

// isEndOfWord is true if the node represents
// end of a word
boolean isEndOfWord;

TrieNode(){
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
children[i] = null;
}
};

static TrieNode root;

// If not present, inserts key into trie
// If the key is prefix of trie node,
// just marks leaf node
static void insert(String key)
{
int level;
int index;
int length = key.length();

TrieNode pCrawl = root;

for (level = 0; level < length; level++)
{
index = key.charAt(level) - 'a';
if (pCrawl.children[index] == null)
pCrawl.children[index] = new TrieNode();

pCrawl = pCrawl.children[index];
}

// mark last node as leaf
pCrawl.isEndOfWord = true;
}

// Returns true if key presents in trie, else false
static boolean search(String key)
{
int level;
int index;
int length = key.length();

TrieNode pCrawl = root;

for (level = 0; level < length; level++)
{
index = key.charAt(level) - 'a';

if (pCrawl.children[index] == null)
return false;

pCrawl = pCrawl.children[index];
}

return (pCrawl.isEndOfWord);
}

}