Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define the TreeNode struct with optional left and right children.
DSA Rust
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>[1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using semicolon instead of comma after struct fields.
Missing comma causing syntax errors.
✗ Incorrect
In Rust struct fields are separated by commas. So a comma is needed after the right field declaration.
2fill in blank
mediumComplete the code to calculate the maximum depth of a binary tree node recursively.
DSA Rust
fn max_depth(node: &Option<Box<TreeNode>>) -> i32 {
match node {
None => 0,
Some(n) => 1 + std::cmp::max(max_depth(&n.left), [1])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use a reference causing type errors.
Calling max_depth on the wrong child.
✗ Incorrect
We must recursively call max_depth on the right child with a reference, so &n.right is correct.
3fill in blank
hardComplete the return statement in the diameter_helper function to return the correct height.
DSA Rust
fn diameter_helper(node: &Option<Box<TreeNode>>, diameter: &mut i32) -> i32 {
match node {
None => 0,
Some(n) => {
let left = diameter_helper(&n.left, diameter);
let right = diameter_helper(&n.right, diameter);
*diameter = std::cmp::max(*diameter, left + right);
1 + [1]
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning sum instead of max causing incorrect height.
Returning product or difference causing wrong results.
✗ Incorrect
The function returns the height of the node, which is max of left and right subtree heights plus one (already added outside).
4fill in blank
hardFill both blanks to complete the diameter_of_binary_tree function that initializes diameter and calls helper.
DSA Rust
fn diameter_of_binary_tree(root: Option<Box<TreeNode>>) -> i32 {
let mut diameter = [1];
diameter_helper(&root, &mut diameter);
[2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing diameter to 1 instead of 0.
Returning wrong variable or nothing.
✗ Incorrect
Diameter starts at 0 and after helper call, we return the diameter value.
5fill in blank
hardFill all three blanks to correctly update diameter and return height in diameter_helper.
DSA Rust
fn diameter_helper(node: &Option<Box<TreeNode>>, diameter: &mut i32) -> i32 {
match node {
None => 0,
Some(n) => {
let left = diameter_helper(&n.left, diameter);
let right = diameter_helper(&n.right, diameter);
*diameter = std::cmp::max(*diameter, [1]);
[2] + [3]
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Updating diameter with incorrect values.
Returning sum instead of max plus one for height.
✗ Incorrect
Diameter is updated with left + right path length. Height returned is std::cmp::max(left, right) + 1.
