Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new binary tree node with given value.
DSA Rust
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
};
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode {
val: [1],
left: None,
right: None,
}
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of the input value.
Using None which is for options, not for integer values.
✗ Incorrect
The new function should assign the input parameter 'val' to the node's val field.
2fill in blank
mediumComplete the code to add the left child to a TreeNode.
DSA Rust
impl TreeNode {
fn add_left(&mut self, child: TreeNode) {
self.left = Some(Box::new([1]));
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using Box::new(child) inside Box::new again causes error.
Using *child tries to dereference a non-pointer.
✗ Incorrect
We wrap the given child node in Box::new and then in Some. Here, Box::new is already called outside, so just use 'child'.
3fill in blank
hardFix the error in the recursive function to collect left side view nodes.
DSA Rust
fn left_side_view(root: &Option<Box<TreeNode>>, level: usize, result: &mut Vec<i32>) {
if let Some(node) = root {
if level == [1] {
result.push(node.val);
}
left_side_view(&node.left, level + 1, result);
left_side_view(&node.right, level + 1, result);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing level with 0 always adds only root.
Comparing level with level is always true, causing duplicates.
✗ Incorrect
We add the node's value only if the current level equals the number of nodes already in result, ensuring the first node at each level is recorded.
4fill in blank
hardFill both blanks to complete the function that returns the left side view of a binary tree.
DSA Rust
fn left_view(root: Option<Box<TreeNode>>) -> Vec<i32> {
let mut result = Vec::new();
[1](&root, 0, &mut result);
result
}
fn [2](root: &Option<Box<TreeNode>>, level: usize, result: &mut Vec<i32>) {
if let Some(node) = root {
if level == result.len() {
result.push(node.val);
}
[2](&node.left, level + 1, result);
[2](&node.right, level + 1, result);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the helper function causes errors.
Calling the function with wrong parameters.
✗ Incorrect
The helper function is named 'left_side_view' and is called inside 'left_view'.
5fill in blank
hardFill all three blanks to create a complete working example that builds a tree and prints its left side view.
DSA Rust
fn main() {
let mut root = TreeNode::new(1);
root.add_left(TreeNode::new([1]));
root.add_right(TreeNode::new([2]));
let left_view_result = left_view(Some(Box::new(root)));
println!("Left side view: {:?}", [3]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping left and right child values.
Printing the root instead of the left view result.
✗ Incorrect
We add left child with value 2, right child with value 3, and print the left_view_result vector.
