File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ function TrieNode ( ) {
2+ this . children = { } ;
3+ this . isEnd = false ;
4+ }
5+
6+ function Trie ( ) {
7+ this . root = new TrieNode ( ) ;
8+ }
9+
10+ Trie . prototype . insert = function ( word ) {
11+ let node = this . root ;
12+ for ( let char of word ) {
13+ if ( ! node . children [ char ] ) {
14+ node . children [ char ] = new TrieNode ( ) ;
15+ }
16+ node = node . children [ char ] ;
17+ }
18+ node . isEnd = true ;
19+ } ;
20+
21+ Trie . prototype . search = function ( word ) {
22+ let node = this . _traverse ( word ) ;
23+ return node !== null && node . isEnd === true ;
24+ } ;
25+
26+ Trie . prototype . startsWith = function ( prefix ) {
27+ return this . _traverse ( prefix ) !== null ;
28+ } ;
29+
30+ Trie . prototype . _traverse = function ( str ) {
31+ let node = this . root ;
32+ for ( let char of str ) {
33+ if ( ! node . children [ char ] ) return null ;
34+ node = node . children [ char ] ;
35+ }
36+ return node ;
37+ } ;
You can’t perform that action at this time.
0 commit comments