class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord = false; } public class Main { public static void main(String[] args) { TrieNode node = new TrieNode(); System.out.println(node.isEndOfWord + ", " + node.children[0]); } }
The boolean field isEndOfWord is initialized to false by default. The children array elements are object references and default to null. So printing node.isEndOfWord and node.children[0] outputs false, null.
class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord = false; } public class Main { public static void main(String[] args) { TrieNode node = new TrieNode(); System.out.println(node.children.length); } }
The children array is created with size 26 to represent all lowercase English letters. So its length is 26.
class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord = false; public TrieNode() { for (int i = 0; i < 26; i++) { children[i] = null; } } }
The loop runs from 0 to 26 inclusive, but the array size is 26, so valid indices are 0 to 25. Accessing children[26] causes ArrayIndexOutOfBoundsException at runtime.
isEndOfWord in a Trie node?The isEndOfWord flag marks that the path to this node forms a complete word stored in the Trie. It helps differentiate words from prefixes.
class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord = false; } public class Main { static TrieNode root = new TrieNode(); public static void insert(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { int index = ch - 'a'; if (node.children[index] == null) { node.children[index] = new TrieNode(); } node = node.children[index]; } node.isEndOfWord = true; } public static void main(String[] args) { insert("cat"); System.out.println(root.children['c' - 'a'].isEndOfWord + ", " + root.children['c' - 'a'].children['a' - 'a'].isEndOfWord + ", " + root.children['c' - 'a'].children['a' - 'a'].children['t' - 'a'].isEndOfWord); } }
When inserting "cat", only the node for 't' is marked as end of word. Nodes for 'c' and 'a' are intermediate and have isEndOfWord false.
