我正在尝试使用go来实现Trie数据结构,但我不熟悉该语言,也不使用地图,并且想知道是否有一些技巧可以解释我的一些递归因此它没有&#39看起来很糟糕。如果我能得到一些关于如何使添加方法更好(更少的代码行)的帮助,也将不胜感激。
刚刚注意到树本身在添加单词时永远不会知道的问题,所以绝对可以解决这个问题!
// 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++)
}
}