Skip to content

Instantly share code, notes, and snippets.

@fractalbach
Created March 10, 2019 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fractalbach/a538866e31b3e15e1c43c831136ce9ed to your computer and use it in GitHub Desktop.
Save fractalbach/a538866e31b3e15e1c43c831136ce9ed to your computer and use it in GitHub Desktop.
Simple Trie using hashmap in each node
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)
}
@fractalbach
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment