classTrie { classTrieNode { boolean end; // int cnt; // 维护节点数量 TrieNode[] children = newTrieNode[26]; } TrieNoderoot=newTrieNode(); voidinsert(String word) { TrieNodecur= root; for (char c : word.toCharArray()) { intindex= (int) c - 97; if (cur.children[index] == null) { cur.children[index] = newTrieNode(); } cur = cur.children[index]; } cur.end = true; } booleansearch(String word) { TrieNodecur= root; for (char c : word.toCharArray()) { intindex= (int) c - 97; if (cur.children[index] == null) returnfalse; cur = cur.children[index]; } return cur.end; } publicvoiddelete(String word) { deleteHelper(root, word, 0); } privatebooleandeleteHelper(TrieNode node, String word, int depth) { if (node == null) returnfalse; if (depth == word.length()) { if (!node.end) returnfalse; node.end = false; return allNull(node.children); // If the current node has no other children, it can be safely removed. } intindex= word.charAt(depth) - 'a'; if (deleteHelper(node.children[index], word, depth + 1)) { // After the recursive call, the child node can be safely removed. node.children[index] = null; return !node.end && allNull(node.children); } returnfalse; } privatebooleanallNull(TrieNode[] arr) { for (TrieNode node : arr) { if (node != null) returnfalse; } returntrue; } }