File tree Expand file tree Collapse file tree 2 files changed +116
-0
lines changed Expand file tree Collapse file tree 2 files changed +116
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Package trie provides Trie data structures in golang.
2
+ //
3
+ // Wikipedia: https://en.wikipedia.org/wiki/Trie
4
+ package trie
5
+
6
+ // Node represents each node in Trie.
7
+ type Node struct {
8
+ children map [rune ]* Node // map children nodes
9
+ isLeaf bool // current node value
10
+ }
11
+
12
+ // NewNode creates a new Trie node with initialized
13
+ // children map.
14
+ func NewNode () * Node {
15
+ n := & Node {}
16
+ n .children = make (map [rune ]* Node )
17
+ n .isLeaf = false
18
+ return n
19
+ }
20
+
21
+ // Insert inserts words at a Trie node.
22
+ func (n * Node ) Insert (s string ) {
23
+ curr := n
24
+ for _ , c := range s {
25
+ next , ok := curr .children [c ]
26
+ if ! ok {
27
+ next = NewNode ()
28
+ curr .children [c ] = next
29
+ }
30
+ curr = next
31
+ }
32
+ curr .isLeaf = true
33
+ }
34
+
35
+ // Find finds words at a Trie node.
36
+ func (n * Node ) Find (s string ) bool {
37
+ curr := n
38
+ for _ , c := range s {
39
+ next , ok := curr .children [c ]
40
+ if ! ok {
41
+ return false
42
+ }
43
+ curr = next
44
+ }
45
+ return true
46
+ }
Original file line number Diff line number Diff line change
1
+ package trie
2
+
3
+ import (
4
+ "testing"
5
+ )
6
+
7
+ func TestTrie (t * testing.T ) {
8
+ n := NewNode ()
9
+
10
+ insertWords := [... ]string {
11
+ "nikola" ,
12
+ "tesla" ,
13
+ }
14
+ checkWords := map [string ]bool {
15
+ "thomas" : false ,
16
+ "edison" : false ,
17
+ "nikola" : true ,
18
+ }
19
+
20
+ for _ , w := range insertWords {
21
+ n .insert (w )
22
+ t .Logf (
23
+ "added \" %s\" to the Trie." ,
24
+ w ,
25
+ )
26
+ }
27
+
28
+ for k , v := range checkWords {
29
+ ok := n .find (k )
30
+ if ok != v {
31
+ t .Fatalf (
32
+ "\" %s\" is supposed to be %sin the Trie." ,
33
+ k ,
34
+ map [bool ]string {true : "" , false : "NOT " }[v ],
35
+ )
36
+ }
37
+ t .Logf (
38
+ "\" %s\" is %sin the Trie." ,
39
+ k ,
40
+ map [bool ]string {true : "" , false : "NOT " }[ok ],
41
+ )
42
+ }
43
+ }
44
+
45
+ func BenchmarkTrie (b * testing.B ) {
46
+ for i := 0 ; i < b .N ; i ++ {
47
+ n := NewNode ()
48
+
49
+ n .insert ("nikola" )
50
+ n .insert ("tesla" )
51
+
52
+ n .find ("thomas" )
53
+ n .find ("edison" )
54
+ n .find ("nikola" )
55
+ }
56
+ }
57
+
58
+ func ExampleNode () {
59
+ // creates a new node
60
+ node := NewNode ()
61
+
62
+ // adds words
63
+ node .insert ("nikola" )
64
+ node .insert ("tesla" )
65
+
66
+ // finds words
67
+ node .find ("thomas" ) // false
68
+ node .find ("edison" ) // false
69
+ node .find ("nikola" ) // true
70
+ }
You can’t perform that action at this time.
0 commit comments