File tree Expand file tree Collapse file tree 5 files changed +29
-31
lines changed
main/java/dataStructures/trie
test/java/dataStructures/trie Expand file tree Collapse file tree 5 files changed +29
-31
lines changed Original file line number Diff line number Diff line change 1
1
package dataStructures .trie ;
2
2
3
3
import java .util .ArrayList ;
4
+ import java .util .HashMap ;
4
5
import java .util .List ;
6
+ import java .util .Map ;
5
7
6
8
/**
7
9
* Implementation of a Trie; Here we consider strings (not case-sensitive)
@@ -13,6 +15,18 @@ public Trie() {
13
15
root = new TrieNode ();
14
16
}
15
17
18
+ private class TrieNode {
19
+ // CHECKSTYLE:OFF: VisibilityModifier
20
+ public Map <Character , TrieNode > children ; // or array of size 26 (assume not case-sensitive) to denote each char
21
+ // CHECKSTYLE:OFF: VisibilityModifier
22
+ public boolean isEnd ; // a marker to indicate whether the path from the root to this node forms a known word
23
+
24
+ public TrieNode () {
25
+ children = new HashMap <Character , TrieNode >();
26
+ isEnd = false ;
27
+ }
28
+ }
29
+
16
30
/**
17
31
* Inserts a word into the trie.
18
32
* @param word
@@ -90,7 +104,7 @@ public void deleteAndPrune(String word) {
90
104
char curr = word .charAt (i );
91
105
TrieNode nodeBeforeCurr = trackNodes .get (i );
92
106
TrieNode nextNode = nodeBeforeCurr .children .get (curr );
93
- if (nextNode .children .size () == 0 ) { // this node essentially doesn't track anything, remove
107
+ if (! nextNode .isEnd && nextNode . children .size () == 0 ) { // node essentially doesn't track anything, remove
94
108
nodeBeforeCurr .children .remove (curr );
95
109
} else { // children.size() > 0; i.e. this node is still useful; no need to further prune upwards
96
110
break ;
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 7
7
import org .junit .Assert ;
8
8
import org .junit .Test ;
9
9
10
- /**
11
- * insert
12
- * search
13
- * delete
14
- * deleteAndPrune
15
- * wordsWithPrefix
16
- * getAllWords
17
- */
18
10
public class TrieTest {
19
11
@ Test
20
12
public void search_shouldFindWordIfExists () {
@@ -72,6 +64,20 @@ public void deleteAndPrune_shouldPrune() {
72
64
Assert .assertTrue (trie .checkNodeExistsAtPosition ("cs3230" , 2 ));
73
65
}
74
66
67
+ @ Test
68
+ public void deleteAndPrune_shouldNotDeletePrefixWords () {
69
+ Trie trie = new Trie ();
70
+ trie .insert ("art" );
71
+ trie .insert ("artist" );
72
+ trie .insert ("artistic" );
73
+ trie .insert ("artistically" );
74
+
75
+ Assert .assertTrue (trie .search ("artistically" ));
76
+ trie .deleteAndPrune ("artistically" );
77
+ Assert .assertTrue (trie .search ("artistic" )); // should not be pruned away
78
+ Assert .assertTrue (trie .search ("art" )); // should not be pruned away
79
+ }
80
+
75
81
@ Test
76
82
public void wordsWithPrefix_shouldDisplayCurrentWordsThatMatches () {
77
83
Trie trie = new Trie ();
You can’t perform that action at this time.
0 commit comments