This program is simple. We first see the TreeNode class—this contains the children node (in a HashMap). We also have get and add() methods.
import java.util.HashMap;
class TreeNode {
boolean word;
HashMap<Character, TreeNode> children = new HashMap<>();
public TreeNode get(char value) {
// Get anode from the HashMap.
return children.getOrDefault(value, null);
}
public TreeNode add(char value, TreeNode node) {
// Add a node if one does not yet exists.
// ... Return the matching node.
children.putIfAbsent(value, node);
return get(value);
}
}
public class Program {
static TreeNode root = new TreeNode();
static void addWord(String value) {
// Add all characters from the string to the tree.
TreeNode node = root;
for (int i = 0; i < value.length(); i++) {
node = node.add(value.charAt(i), node);
}
node.word = true;
}
static boolean exists(String value) {
// See if a word exists in the tree.
TreeNode node = root;
for (int i = 0; i < value.length(); i++) {
node = node.get(value.charAt(i));
if (node == null) {
return false;
}
}
return node.word;
}
public static void main(String[] args) {
// Add three words to the tree.
addWord(
"cat");
addWord(
"bird");
addWord(
"dog");
// These three words should exist.
boolean exists1 = exists(
"cat");
boolean exists2 = exists(
"bird");
boolean exists3 = exists(
"dog");
System.out.println(exists1);
System.out.println(exists2);
System.out.println(exists3);
// These words do not exist.
exists1 = exists(
"fish");
exists2 = exists(
"123456");
exists3 = exists(
"turnip");
System.out.println(exists1);
System.out.println(exists2);
System.out.println(exists3);
}
}
true
true
true
false
false
false