Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node with the given value.
DSA Rust
fn new_node(value: i32) -> Box<Node> {
Box::new(Node {
data: value,
left: None,
right: None,
[1] })
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning a value to parent instead of None
Using Some with incorrect value for parent
✗ Incorrect
The new node should have no parent initially, so 'parent: None' is correct.
2fill in blank
mediumComplete the code to decide to insert the new value in the left subtree.
DSA Rust
if value [1] node.data { node.left = Some(insert(node.left.take(), value)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' for left subtree
Using '==' which is for equality check
✗ Incorrect
If the value is less than the current node's data, it goes to the left subtree.
3fill in blank
hardFix the error in the recursive insert call to correctly handle the right subtree.
DSA Rust
if value > node.data { node.right = Some(insert([1], value)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing node.right directly without take()
Using left child instead of right child
✗ Incorrect
We must take ownership of the right child using 'take()' before recursive insert.
4fill in blank
hardFill the blank to correctly insert a new node when the current node is None.
DSA Rust
if node.is_none() { return Some(Box::new(Node { data: value, left: None, right: None, [1]: None, })); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using left or right instead of parent
Setting child field which does not exist
✗ Incorrect
The parent field should be set to None when creating a new node.
5fill in blank
hardFill all three blanks to complete the insert function returning the updated node.
DSA Rust
fn insert(node: Option<Box<Node>>, value: i32) -> Option<Box<Node>> {
match node {
Some(mut node) => {
if value [1] node.data {
node.left = Some(insert(node.left.take(), value));
} else if value [2] node.data {
node.right = Some(insert(node.right.take(), value));
}
[3]
}
None => {
Some(Box::new(Node {
data: value,
left: None,
right: None,
parent: None,
}))
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators
Not wrapping the node in Some()
✗ Incorrect
Use '<' and '>' to compare values and wrap the updated node in Some(node) at the end.
