@@ -29,27 +29,37 @@ export default class Trie {
29
29
* @return {Trie }
30
30
*/
31
31
deleteWord ( word ) {
32
- function depthFirstDelete ( currentNode , charIndex ) {
33
- if ( charIndex >= word . length ) return ;
32
+ const depthFirstDelete = ( currentNode , charIndex = 0 ) => {
33
+ if ( charIndex >= word . length ) {
34
+ // Return if we're trying to delete the character that is out of word's scope.
35
+ return ;
36
+ }
34
37
35
38
const character = word [ charIndex ] ;
36
39
const nextNode = currentNode . getChild ( character ) ;
37
40
38
- if ( nextNode == null ) return ;
41
+ if ( nextNode == null ) {
42
+ // Return if we're trying to delete a word that has not been added to the Trie.
43
+ return ;
44
+ }
39
45
46
+ // Go deeper.
40
47
depthFirstDelete ( nextNode , charIndex + 1 ) ;
41
48
42
- if ( charIndex === word . length - 1 ) {
49
+ // Since we're going to delete a word let's un-mark its last character isCompleteWord flag.
50
+ if ( charIndex === ( word . length - 1 ) ) {
43
51
nextNode . isCompleteWord = false ;
44
52
}
45
53
46
54
// childNode is deleted only if:
47
55
// - childNode has NO children
48
56
// - childNode.isCompleteWord === false
49
57
currentNode . removeChild ( character ) ;
50
- }
58
+ } ;
59
+
60
+ // Start depth-first deletion from the head node.
61
+ depthFirstDelete ( this . head ) ;
51
62
52
- depthFirstDelete ( this . head , 0 ) ;
53
63
return this ;
54
64
}
55
65
0 commit comments