Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the struct for a binary tree node.
DSA Rust
struct Node {
data: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn new(data: i32) -> Self {
Node {
data,
left: [1],
right: None,
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Some without boxing the node.
Initializing left child with a new node instead of None.
✗ Incorrect
The left child is initially empty, so it should be None.
2fill in blank
mediumComplete the code to insert a node into the binary tree at the correct horizontal distance.
DSA Rust
use std::collections::HashMap;
fn bottom_view(root: &Option<Box<Node>>, hd: i32, map: &mut HashMap<i32, i32>) {
if let Some(node) = root {
map.insert(hd, node.data);
bottom_view(&node.left, hd - 1, map);
[1](&node.right, hd + 1, map);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name causing compilation error.
Not calling recursively on the right child.
✗ Incorrect
The function calls itself recursively on the right child to update the map.
3fill in blank
hardFix the error in the code to print the bottom view of the binary tree in order of horizontal distance.
DSA Rust
fn print_bottom_view(map: &HashMap<i32, i32>) {
let mut keys: Vec<i32> = map.keys().cloned().collect();
keys.sort();
for key in keys {
print!("{} ", [1]);
}
println!();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using map[key] which is invalid syntax in Rust.
Using key instead of value in print.
✗ Incorrect
HashMap values are accessed with get(&key) and unwrap to get the value.
4fill in blank
hardFill both blanks to create a HashMap and call the bottom_view function starting from root with horizontal distance 0.
DSA Rust
use std::collections::HashMap;
fn main() {
let mut map: HashMap<i32, i32> = [1];
let root = Some(Box::new(Node::new(10)));
bottom_view(&root, [2], &mut map);
print_bottom_view(&map);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using HashMap::default() which is less common.
Starting horizontal distance at 1 instead of 0.
✗ Incorrect
We create an empty HashMap with HashMap::new() and start horizontal distance at 0.
5fill in blank
hardFill all three blanks to update the bottom view map with the current node's data and recursively traverse left and right children with updated horizontal distances.
DSA Rust
fn bottom_view(root: &Option<Box<Node>>, hd: i32, map: &mut HashMap<i32, i32>) {
if let Some(node) = root {
map.[1](hd, node.data);
bottom_view(&node.[2], hd [3] 1, map);
bottom_view(&node.right, hd + 1, map);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using remove instead of insert.
Using '+' instead of '-' for left child horizontal distance.
✗ Incorrect
We insert the node data at horizontal distance, recurse left with hd - 1, and right with hd + 1.
