Trie Examples (#3466)

* Implement Trie

* Implement TrieTest

* Delete testDelete method

* Refactorings

* Refactor Trie

* Refactor TrieNode

* Refactor Trie
This commit is contained in:
Grzegorz Piwowarek
2018-01-20 11:54:24 +01:00
committed by GitHub
parent 7e7ccc7eb3
commit 0293c65f77
3 changed files with 175 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
package com.baeldung.trie;
public class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildren()
.get(ch);
if (node == null) {
node = new TrieNode();
current.getChildren()
.put(ch, node);
}
current = node;
}
current.setEndOfWord(true);
}
public boolean find(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildren()
.get(ch);
if (node == null) {
return false;
}
current = node;
}
return current.isEndOfWord();
}
public void delete(String word) {
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
if (!current.isEndOfWord()) {
return false;
}
current.setEndOfWord(false);
return current.getChildren()
.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.getChildren()
.get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
if (shouldDeleteCurrentNode) {
current.getChildren()
.remove(ch);
return current.getChildren().isEmpty();
}
return false;
}
public boolean containsNode(String word) {
return find(word);
}
public boolean isEmpty() {
return root == null;
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.trie;
import java.util.HashMap;
import java.util.Map;
class TrieNode {
private Map<Character, TrieNode> children;
private boolean endOfWord;
public TrieNode() {
children = new HashMap<>();
endOfWord = false;
}
public Map<Character, TrieNode> getChildren() {
return children;
}
public void setChildren(Map<Character, TrieNode> children) {
this.children = children;
}
public boolean isEndOfWord() {
return endOfWord;
}
public void setEndOfWord(boolean endOfWord) {
this.endOfWord = endOfWord;
}
}