Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the minimum value in the BST by going left.
DSA Rust
fn find_min(node: &Option<Box<TreeNode>>) -> i32 {
let mut current = node;
while let Some(ref n) = current {
if n.[1].is_none() {
return n.val;
}
current = &n.[2];
}
panic!("Tree is empty");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' instead of 'left' to find the minimum.
Trying to return the value before checking if left child exists.
✗ Incorrect
The minimum element in a BST is found by continuously going to the left child until there is no left child.
2fill in blank
mediumComplete the code to recursively find the minimum value in the BST.
DSA Rust
fn find_min_recursive(node: &Option<Box<TreeNode>>) -> i32 {
match node {
Some(ref n) => {
if n.[1].is_none() {
n.val
} else {
find_min_recursive(&n.[2])
}
}
None => panic!("Tree is empty"),
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking right child instead of left.
Returning value without checking if left child exists.
✗ Incorrect
Recursively check if the left child exists; if not, current node is minimum.
3fill in blank
hardFix the error in the loop condition to correctly traverse left children.
DSA Rust
fn find_min(node: &Option<Box<TreeNode>>) -> i32 {
let mut current = node;
while current.[1]() {
if current.as_ref().unwrap().left.is_none() {
return current.as_ref().unwrap().val;
}
current = ¤t.as_ref().unwrap().left;
}
panic!("Tree is empty");
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding redundant conditions causing syntax errors.
Using '||' instead of '&&' or no condition.
✗ Incorrect
The while loop should continue while current is Some, using is_some() to check.
4fill in blank
hardFill both blanks to create a function that returns the minimum value or None if tree is empty.
DSA Rust
fn find_min_option(node: &Option<Box<TreeNode>>) -> Option<i32> {
let mut current = node;
while let Some(ref n) = current {
if n.[1].is_none() {
return Some(n.val);
}
current = &n.[2];
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Using right child instead of left.
Returning value directly instead of Some(value).
✗ Incorrect
To find minimum, check if left child is None and move left each iteration.
5fill in blank
hardFill all three blanks to create a recursive function returning Option<i32> for minimum value.
DSA Rust
fn find_min_recursive_option(node: &Option<Box<TreeNode>>) -> Option<i32> {
match node {
Some(ref n) => {
if n.[1].is_none() {
Some(n.[2])
} else {
find_min_recursive_option(&n.[3])
}
}
None => None,
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using right child instead of left.
Returning value without wrapping in Some.
✗ Incorrect
Check if left child is None, then return Some(value), else recurse left.
