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 11package dataStructures .trie ;
22
33import java .util .ArrayList ;
4+ import java .util .HashMap ;
45import java .util .List ;
6+ import java .util .Map ;
57
68/**
79 * Implementation of a Trie; Here we consider strings (not case-sensitive)
@@ -13,6 +15,18 @@ public Trie() {
1315 root = new TrieNode ();
1416 }
1517
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+
1630 /**
1731 * Inserts a word into the trie.
1832 * @param word
@@ -90,7 +104,7 @@ public void deleteAndPrune(String word) {
90104 char curr = word .charAt (i );
91105 TrieNode nodeBeforeCurr = trackNodes .get (i );
92106 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
94108 nodeBeforeCurr .children .remove (curr );
95109 } else { // children.size() > 0; i.e. this node is still useful; no need to further prune upwards
96110 break ;
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 77import org .junit .Assert ;
88import org .junit .Test ;
99
10- /**
11- * insert
12- * search
13- * delete
14- * deleteAndPrune
15- * wordsWithPrefix
16- * getAllWords
17- */
1810public class TrieTest {
1911 @ Test
2012 public void search_shouldFindWordIfExists () {
@@ -72,6 +64,20 @@ public void deleteAndPrune_shouldPrune() {
7264 Assert .assertTrue (trie .checkNodeExistsAtPosition ("cs3230" , 2 ));
7365 }
7466
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+
7581 @ Test
7682 public void wordsWithPrefix_shouldDisplayCurrentWordsThatMatches () {
7783 Trie trie = new Trie ();
You can’t perform that action at this time.
0 commit comments