I am trying to implement the Trie data structure using go but I am not that familiar with the language nor using a map and was wondering if there were some tips to how I can factor out some of my recursion so it doesn't look so bad. Also would appreciate it if I could get some help on how to make just the add method better (less lines of code).
Just noticed the problem where the tree itself would never know when a word is added so definitely a solution to that would be great!
// The overall tree
type TrieTree struct {
root TrieNode
count int
}
// The node for each character inside the tree
type TrieNode struct {
letter string // this is the value of the current node
isWord bool // if this letter + all of its parents make a word set = to true
children map[string]*TrieNode // maps children nodes
}
//method for adding a word into the tree
func (root *TrieNode, entry string) AddEntry() {
//in case someone is trying to mess you up
if (entry != nil || len(entry) != 0 || root != nil) {
entry = strings.ToLower(entry)
AddEntryHelper(root, entry, 0)
}
}
func (node *TrieNode, entry string, count int) AddEntryHelper() {
// the last one and no child yet
if(node.children == nil && count == len(entry)-1) {
node.children=(map[string(entry[count])]=TrieNode{string(entry[count]), true, nil})
// no children and not last one
} else if(node.children == nil && count != len(entry)-1) {
node.children=(map[string(entry[count])]=TrieNode{string(entry[count]), false, nil})
AddEntryHelper(node.children[string(entry[count])], entry, count++)
// last one and child exist
} else if (node.children != nil && count == len(entry)-1) {
node.children[string(entry[count])].isWord = true
// children node exists and just need to recurse down
} else {
AddEntryHelper(node.children[string(entry[count])], entry, count++)
}
}