Complete the code to create a new Trie node.
func NewTrieNode() *TrieNode {
return &TrieNode{
children: make(map[rune]*TrieNode),
isEnd: [1],
}
}The new Trie node should start with isEnd set to false because it does not represent the end of a word yet.
Complete the code to insert a word into the Trie.
func (t *Trie) Insert(word string) {
node := t.root
for _, ch := range word {
if node.children[ch] == nil {
node.children[ch] = NewTrieNode()
}
node = node.children[[1]]
}
node.isEnd = true
}We move to the child node corresponding to the current character ch in the word.
Fix the error in the search function to check if a word exists in the Trie.
func (t *Trie) Search(word string) bool {
node := t.root
for _, ch := range word {
if node.children[ch] == nil {
return false
}
node = node.children[ch]
}
return node.[1]
}After traversing all characters, we return isEnd to confirm the word ends here.
Fill both blanks to collect all words starting with a prefix using DFS.
func (t *Trie) collectWords(node *TrieNode, prefix string, results *[]string) {
if node.[1] {
*results = append(*results, prefix)
}
for ch, child := range node.[2] {
t.collectWords(child, prefix+string(ch), results)
}
}Check isEnd to add words, and loop over children to explore next nodes.
Fill all three blanks to implement the Autocomplete function returning all words with a prefix.
func (t *Trie) Autocomplete(prefix string) []string {
node := t.root
for _, ch := range prefix {
if node.children[[1]] == nil {
return []string{}
}
node = node.children[ch]
}
results := []string{}
t.collectWords(node, [2], &results)
return [3]
}Use ch to check children, pass prefix to collectWords, and return results array.