Created
March 10, 2019 09:29
-
-
Save fractalbach/a538866e31b3e15e1c43c831136ce9ed to your computer and use it in GitHub Desktop.
Simple Trie using hashmap in each node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type node struct { | |
terminal bool | |
m map[rune]*node | |
} | |
type trie struct { | |
root *node | |
} | |
func NewNode() *node { | |
return &node{ | |
m: make(map[rune]*node), | |
} | |
} | |
func NewTrie() *trie { | |
return &trie{root: NewNode()} | |
} | |
func (t *trie) add(s string) { | |
if len(s) <= 0 { | |
return | |
} | |
current := t.root | |
var next *node | |
var ok bool | |
for _, r := range s { | |
next, ok = current.m[r] | |
if ok { | |
current = next | |
continue | |
} | |
current.m[r] = NewNode() | |
current = current.m[r] | |
} | |
current.terminal = true | |
} | |
func (t *trie) addlots(args ...string) { | |
for _, s := range args { | |
t.add(s) | |
} | |
} | |
func (t *trie) display() { | |
t.root.display(0) | |
} | |
func (n *node) display(depth int) { | |
for k, v := range n.m { | |
fmt.Print(spaces(depth)) | |
fmt.Printf("%c", k) | |
if v.terminal { | |
fmt.Print("*") | |
} | |
fmt.Println() | |
v.display(depth + 1) | |
} | |
} | |
func spaces(n int) string { | |
s := "" | |
for i := 0; i < n; i++ { | |
s += " " | |
} | |
return s | |
} | |
func main() { | |
t := NewTrie() | |
t.add("hello") | |
t.add("hell") | |
t.add("herro") | |
t.add("derp") | |
t.add("dog") | |
t.display() | |
fmt.Println(t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/nw3IJ5lTHZp