Skip to content

Instantly share code, notes, and snippets.

@johnnyeric
Last active March 11, 2022 15:50
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 johnnyeric/110893a0f2c344b67be3e417d55c6cad to your computer and use it in GitHub Desktop.
Save johnnyeric/110893a0f2c344b67be3e417d55c6cad to your computer and use it in GitHub Desktop.
Simple Trie implementation in Golang
package trie
type Node struct {
Children [26]*Node
Char rune
IsRoot bool
IsWordEnd bool
}
type Trie struct {
Root *Node
}
func NewTrie() *Trie {
return &Trie{
Root: &Node{
IsRoot: true,
},
}
}
func (t *Trie) AddWord(word string) {
curr := t.Root
for _, char := range word {
idx := char - 'a'
if curr.Children[idx] == nil {
curr.Children[idx] = &Node{
IsRoot: false,
Char: char,
}
}
curr = curr.Children[idx]
}
curr.IsWordEnd = true
}
func (t *Trie) Find(word string) bool {
curr := t.findNode(word)
return curr.IsWordEnd
}
func (t *Trie) findNode(word string) *Node {
curr := t.Root
for _, char := range word {
if char < 97 || char > 122 {
continue
}
idx := char - 'a'
if curr.Children[idx] == nil {
return nil
}
curr = curr.Children[idx]
}
return curr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment