Complete the code to create a new Trie node with an empty children map.
struct TrieNode {
children: std::collections::HashMap<char, TrieNode>,
is_end_of_word: bool,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: [1],
is_end_of_word: false,
}
}
}We use HashMap::new() to create an empty map for children nodes.
Complete the code to insert a character into the Trie children if it does not exist.
impl TrieNode {
fn insert_char(&mut self, ch: char) {
self.children.entry(ch).or_insert([1]);
}
}We insert a new TrieNode for the character if it is not already present.
Fix the error in the search function to correctly check if a character exists in children.
impl TrieNode {
fn search_char(&self, ch: char) -> bool {
self.children.[1](&ch)
}
}contains_key checks if the map has the given key.
Fill both blanks to insert a word into the Trie and mark the end of the word.
impl TrieNode {
fn insert_word(&mut self, word: &str) {
let mut node = self;
for ch in word.chars() {
node = node.children.entry(ch).or_insert([1]);
}
node.[2] = true;
}
}Insert new TrieNodes for characters and mark the last node's is_end_of_word as true.
Fill all three blanks to collect all words with a given prefix using recursion.
impl TrieNode {
fn collect_words(&self, prefix: String, results: &mut Vec<String>) {
if self.[1] {
results.push(prefix.clone());
}
for (ch, node) in &self.[2] {
let mut new_prefix = prefix.clone();
new_prefix.push([3]);
node.collect_words(new_prefix, results);
}
}
}Check is_end_of_word, iterate over children, and append the character ch to prefix.
