Skip to content

Improve TrieImp.java comments, add unit tests and enhance readability #5526

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 12 commits into from
Oct 5, 2024
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,7 @@
* [SameTreesCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java)
* [SplayTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java)
* [TreeTestUtils](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java)
* [TrieImpTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/TrieImpTest.java)
* [VerticalOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java)
* [ZigzagTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java)
* divideandconquer
Expand Down
130 changes: 65 additions & 65 deletions src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
package com.thealgorithms.datastructures.trees;

import java.util.Scanner;

/**
* Trie Data structure implementation without any libraries
* Trie Data structure implementation without any libraries.
* <p>
* The Trie (also known as a prefix tree) is a special tree-like data structure
* that is used to store a dynamic set or associative array where the keys are
* usually strings. It is highly efficient for prefix-based searches.
* <p>
* This implementation supports basic Trie operations like insertion, search,
* and deletion.
* <p>
* Each node of the Trie represents a character and has child nodes for each
* possible character.
*
* @author <a href="https://github.com/dheeraj92">Dheeraj Kumar Barnwal</a>
*/
public class TrieImp {

/**
* Represents a Trie Node that stores a character and pointers to its children.
* Each node has an array of 26 children (one for each letter from 'a' to 'z').
*/
public class TrieNode {

TrieNode[] child;
boolean end;

/**
* Constructor to initialize a TrieNode with an empty child array
* and set end to false.
*/
public TrieNode() {
child = new TrieNode[26];
end = false;
Expand All @@ -22,10 +38,22 @@ public TrieNode() {

private final TrieNode root;

/**
* Constructor to initialize the Trie.
* The root node is created but doesn't represent any character.
*/
public TrieImp() {
root = new TrieNode();
}

/**
* Inserts a word into the Trie.
* <p>
* The method traverses the Trie from the root, character by character, and adds
* nodes if necessary. It marks the last node of the word as an end node.
*
* @param word The word to be inserted into the Trie.
*/
public void insert(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
Expand All @@ -39,6 +67,16 @@ public void insert(String word) {
currentNode.end = true;
}

/**
* Searches for a word in the Trie.
* <p>
* This method traverses the Trie based on the input word and checks whether
* the word exists. It returns true if the word is found and its end flag is
* true.
*
* @param word The word to search in the Trie.
* @return true if the word exists in the Trie, false otherwise.
*/
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
Expand All @@ -52,6 +90,17 @@ public boolean search(String word) {
return currentNode.end;
}

/**
* Deletes a word from the Trie.
* <p>
* The method traverses the Trie to find the word and marks its end flag as
* false.
* It returns true if the word was successfully deleted, false if the word
* wasn't found.
*
* @param word The word to be deleted from the Trie.
* @return true if the word was found and deleted, false if it was not found.
*/
public boolean delete(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
Expand All @@ -69,75 +118,26 @@ public boolean delete(String word) {
return false;
}

/**
* Helper method to print a string to the console.
*
* @param print The string to be printed.
*/
public static void sop(String print) {
System.out.println(print);
}

/**
* Regex to check if word contains only a-z character
* Validates if a given word contains only lowercase alphabetic characters
* (a-z).
* <p>
* The method uses a regular expression to check if the word matches the pattern
* of only lowercase letters.
*
* @param word The word to be validated.
* @return true if the word is valid (only a-z), false otherwise.
*/
public static boolean isValid(String word) {
return word.matches("^[a-z]+$");
}

public static void main(String[] args) {
TrieImp obj = new TrieImp();
String word;
@SuppressWarnings("resource") Scanner scan = new Scanner(System.in);
sop("string should contain only a-z character for all operation");
while (true) {
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
try {
int t = scan.nextInt();
switch (t) {
case 1:
word = scan.next();
if (isValid(word)) {
obj.insert(word);
} else {
sop("Invalid string: allowed only a-z");
}
break;
case 2:
word = scan.next();
boolean resS = false;
if (isValid(word)) {
resS = obj.search(word);
} else {
sop("Invalid string: allowed only a-z");
}
if (resS) {
sop("word found");
} else {
sop("word not found");
}
break;
case 3:
word = scan.next();
boolean resD = false;
if (isValid(word)) {
resD = obj.delete(word);
} else {
sop("Invalid string: allowed only a-z");
}
if (resD) {
sop("word got deleted successfully");
} else {
sop("word not found");
}
break;
case 4:
sop("Quit successfully");
System.exit(1);
break;
default:
sop("Input int from 1-4");
break;
}
} catch (Exception e) {
String badInput = scan.next();
sop("This is bad input: " + badInput);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.thealgorithms.datastructures.trees;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class TrieImpTest {
private TrieImp trie;

@BeforeEach
public void setUp() {
trie = new TrieImp();
}

@Test
public void testInsertAndSearchBasic() {
String word = "hello";
trie.insert(word);
assertTrue(trie.search(word), "Search should return true for an inserted word.");
}

@Test
public void testSearchNonExistentWord() {
String word = "world";
assertFalse(trie.search(word), "Search should return false for a non-existent word.");
}

@Test
public void testInsertAndSearchMultipleWords() {
String word1 = "cat";
String word2 = "car";
trie.insert(word1);
trie.insert(word2);

assertTrue(trie.search(word1), "Search should return true for an inserted word.");
assertTrue(trie.search(word2), "Search should return true for another inserted word.");
assertFalse(trie.search("dog"), "Search should return false for a word not in the Trie.");
}

@Test
public void testDeleteExistingWord() {
String word = "remove";
trie.insert(word);
assertTrue(trie.delete(word), "Delete should return true for an existing word.");
assertFalse(trie.search(word), "Search should return false after deletion.");
}

@Test
public void testDeleteNonExistentWord() {
String word = "nonexistent";
assertFalse(trie.delete(word), "Delete should return false for a non-existent word.");
}

@Test
public void testInsertAndSearchPrefix() {
String prefix = "pre";
String word = "prefix";
trie.insert(prefix);
trie.insert(word);

assertTrue(trie.search(prefix), "Search should return true for an inserted prefix.");
assertTrue(trie.search(word), "Search should return true for a word with the prefix.");
assertFalse(trie.search("pref"), "Search should return false for a prefix that is not a full word.");
}

@Test
public void testIsValidWord() {
assertTrue(TrieImp.isValid("validword"), "Word should be valid (only lowercase letters).");
assertFalse(TrieImp.isValid("InvalidWord"), "Word should be invalid (contains uppercase letters).");
assertFalse(TrieImp.isValid("123abc"), "Word should be invalid (contains numbers).");
assertFalse(TrieImp.isValid("hello!"), "Word should be invalid (contains special characters).");
assertFalse(TrieImp.isValid(""), "Empty string should be invalid.");
}
}
Loading