1+ package com .baeldung .trie ;
2+
3+ public class Trie {
4+ private TrieNode root ;
5+
6+ public Trie () {
7+ root = new TrieNode ();
8+ }
9+
10+ public void insert (String word ) {
11+ TrieNode current = root ;
12+ for (int i = 0 ; i < word .length (); i ++) {
13+ char ch = word .charAt (i );
14+ TrieNode node = current .getChildren ()
15+ .get (ch );
16+ if (node == null ) {
17+ node = new TrieNode ();
18+ current .getChildren ()
19+ .put (ch , node );
20+ }
21+ current = node ;
22+ }
23+ current .setEndOfWord (true );
24+ }
25+
26+ public boolean find (String word ) {
27+ TrieNode current = root ;
28+ for (int i = 0 ; i < word .length (); i ++) {
29+ char ch = word .charAt (i );
30+ TrieNode node = current .getChildren ()
31+ .get (ch );
32+ if (node == null ) {
33+ return false ;
34+ }
35+ current = node ;
36+ }
37+ return current .isEndOfWord ();
38+ }
39+
40+ public void delete (String word ) {
41+ delete (root , word , 0 );
42+ }
43+
44+ private boolean delete (TrieNode current , String word , int index ) {
45+ if (index == word .length ()) {
46+ if (!current .isEndOfWord ()) {
47+ return false ;
48+ }
49+ current .setEndOfWord (false );
50+ return current .getChildren ()
51+ .size () == 0 ;
52+ }
53+ char ch = word .charAt (index );
54+ TrieNode node = current .getChildren ()
55+ .get (ch );
56+ if (node == null ) {
57+ return false ;
58+ }
59+ boolean shouldDeleteCurrentNode = delete (node , word , index + 1 );
60+
61+ if (shouldDeleteCurrentNode ) {
62+ current .getChildren ()
63+ .remove (ch );
64+ return current .getChildren ()
65+ .size () == 0 ;
66+ }
67+ return false ;
68+ }
69+
70+ public boolean containsNode (String word ) {
71+ return find (word );
72+ }
73+
74+ public boolean isEmpty () {
75+ return root == null ;
76+ }
77+
78+ }
0 commit comments