@@ -29,27 +29,37 @@ export default class Trie {
2929 * @return {Trie }
3030 */
3131 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+ }
3437
3538 const character = word [ charIndex ] ;
3639 const nextNode = currentNode . getChild ( character ) ;
3740
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+ }
3945
46+ // Go deeper.
4047 depthFirstDelete ( nextNode , charIndex + 1 ) ;
4148
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 ) ) {
4351 nextNode . isCompleteWord = false ;
4452 }
4553
4654 // childNode is deleted only if:
4755 // - childNode has NO children
4856 // - childNode.isCompleteWord === false
4957 currentNode . removeChild ( character ) ;
50- }
58+ } ;
59+
60+ // Start depth-first deletion from the head node.
61+ depthFirstDelete ( this . head ) ;
5162
52- depthFirstDelete ( this . head , 0 ) ;
5363 return this ;
5464 }
5565
0 commit comments