@@ -9,26 +9,23 @@ public class Trie {
99
1010 public void insert (String word ) {
1111 TrieNode current = root ;
12+
1213 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 ;
14+ current = current .getChildren ().computeIfAbsent (word .charAt (i ), c -> new TrieNode ());
2215 }
2316 current .setEndOfWord (true );
2417 }
2518
26- public boolean find (String word ) {
19+ public boolean delete (String word ) {
20+ return delete (root , word , 0 );
21+ }
22+
23+ public boolean containsNode (String word ) {
2724 TrieNode current = root ;
25+
2826 for (int i = 0 ; i < word .length (); i ++) {
2927 char ch = word .charAt (i );
30- TrieNode node = current .getChildren ()
31- .get (ch );
28+ TrieNode node = current .getChildren ().get (ch );
3229 if (node == null ) {
3330 return false ;
3431 }
@@ -37,8 +34,8 @@ public boolean find(String word) {
3734 return current .isEndOfWord ();
3835 }
3936
40- public void delete ( String word ) {
41- delete ( root , word , 0 ) ;
37+ public boolean isEmpty ( ) {
38+ return root == null ;
4239 }
4340
4441 private boolean delete (TrieNode current , String word , int index ) {
@@ -47,30 +44,19 @@ private boolean delete(TrieNode current, String word, int index) {
4744 return false ;
4845 }
4946 current .setEndOfWord (false );
50- return current .getChildren ()
51- .size () == 0 ;
47+ return current .getChildren ().isEmpty ();
5248 }
5349 char ch = word .charAt (index );
54- TrieNode node = current .getChildren ()
55- .get (ch );
50+ TrieNode node = current .getChildren ().get (ch );
5651 if (node == null ) {
5752 return false ;
5853 }
5954 boolean shouldDeleteCurrentNode = delete (node , word , index + 1 );
6055
6156 if (shouldDeleteCurrentNode ) {
62- current .getChildren ()
63- .remove (ch );
57+ current .getChildren ().remove (ch );
6458 return current .getChildren ().isEmpty ();
6559 }
6660 return false ;
6761 }
68-
69- public boolean containsNode (String word ) {
70- return find (word );
71- }
72-
73- public boolean isEmpty () {
74- return root == null ;
75- }
7662}
0 commit comments