File tree Expand file tree Collapse file tree 1 file changed +24
-15
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +24
-15
lines changed Original file line number Diff line number Diff line change @@ -7,6 +7,23 @@ var Trie = function () {
77 this . head = new Node ( ) ;
88} ;
99
10+ /**
11+ * @param {string } str
12+ * @return {TrieNode | null }
13+ */
14+ Trie . prototype . _traverse = function ( str ) {
15+ let current = this . head ;
16+
17+ for ( const chr of str ) {
18+ if ( ! current . children . has ( chr ) ) {
19+ return null ;
20+ }
21+ current = current . children . get ( chr ) ;
22+ }
23+
24+ return current ;
25+ } ;
26+
1027/**
1128 * @param {string } word
1229 * @return {void }
@@ -30,32 +47,24 @@ Trie.prototype.insert = function (word) {
3047 * @return {boolean }
3148 */
3249Trie . prototype . search = function ( word ) {
33- let current = this . head ;
34-
35- for ( const chr of word ) {
36- if ( ! current . children . has ( chr ) ) {
37- return false ;
38- }
50+ const node = this . _traverse ( word ) ;
3951
40- current = current . children . get ( chr ) ;
52+ if ( ! node ) {
53+ return false ;
4154 }
4255
43- return current . isEnd ;
56+ return node . isEnd ;
4457} ;
4558
4659/**
4760 * @param {string } prefix
4861 * @return {boolean }
4962 */
5063Trie . prototype . startsWith = function ( prefix ) {
51- let current = this . head ;
64+ const node = this . _traverse ( prefix ) ;
5265
53- for ( const chr of prefix ) {
54- if ( ! current . children . has ( chr ) ) {
55- return false ;
56- }
57-
58- current = current . children . get ( chr ) ;
66+ if ( ! node ) {
67+ return false ;
5968 }
6069
6170 return true ;
You can’t perform that action at this time.
0 commit comments