Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a binary tree node struct with an integer value.
DSA Rust
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
impl TreeNode {
fn new([1]: i32) -> Self {
TreeNode {
val: val,
left: None,
right: None,
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the struct field without mapping it.
Forgetting to define the parameter.
✗ Incorrect
The constructor parameter should be named 'val' to match the field 'val' in the struct.
2fill in blank
mediumComplete the code to create a new TreeNode with value 5.
DSA Rust
let root = TreeNode::new([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Passing 0 or other values instead of 5.
Forgetting to pass any value.
✗ Incorrect
We want to create a node with value 5, so pass 5 to the new function.
3fill in blank
hardFix the error in the code to assign a left child node to root.
DSA Rust
root.left = Some(Box::new(TreeNode::new([1])));Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string instead of an integer.
Assigning None instead of Some(Box::new(...)).
✗ Incorrect
The left child node should be created with an integer value, here 5.
4fill in blank
hardFill both blanks to define a function that returns true if the node has no children.
DSA Rust
impl TreeNode {
fn is_leaf(&self) -> bool {
self.left == [1] && self.right == [2]
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Some(...) instead of None.
Returning true or false directly instead of comparing.
✗ Incorrect
A leaf node has no children, so both left and right should be None.
5fill in blank
hardFill all three blanks to define a method that sets the right child node with a given value.
DSA Rust
impl TreeNode {
fn set_right(&mut self, [1]: i32) {
self.right = Some(Box::new(TreeNode::new([2])));
}
fn get_right_val(&self) -> Option<i32> {
self.right.as_ref().map(|node| node.[3])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent parameter or field names.
Accessing a non-existent field.
✗ Incorrect
The parameter name and field name is 'val' to match the struct field; get_right_val returns node.val.
