Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the maximum value in a BST by moving to the right child.
DSA Rust
fn find_max(node: &Option<Box<TreeNode>>) -> i32 {
let mut current = node;
while let Some(ref n) = current {
if n.right.is_none() {
return n.val;
}
current = &n.[1];
}
panic!("Empty tree");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using left child instead of right child.
Returning the root value without traversal.
✗ Incorrect
To find the maximum element in a BST, we keep moving to the right child until there is no right child left.
2fill in blank
mediumComplete the code to handle the case when the BST is empty by returning None.
DSA Rust
fn find_max_option(node: &Option<Box<TreeNode>>) -> Option<i32> {
let mut current = node;
while let Some(ref n) = current {
if n.right.is_none() {
return Some(n.val);
}
current = &n.[1];
}
[2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning Some(0) for empty tree instead of None.
Using left child for traversal.
✗ Incorrect
We move to the right child until none exists, then return the value wrapped in Some. If the tree is empty, return None.
3fill in blank
hardFix the error in the code to correctly find the maximum value recursively.
DSA Rust
fn find_max_recursive(node: &Option<Box<TreeNode>>) -> i32 {
match node {
None => panic!("Empty tree"),
Some(ref n) => {
if n.[1].is_none() {
n.val
} else {
find_max_recursive(&n.right)
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking left child instead of right child.
Returning node value without recursion.
✗ Incorrect
The maximum value is found by recursively going to the right child until there is no right child.
4fill in blank
hardFill both blanks to create a function that returns the maximum value or None if the tree is empty.
DSA Rust
fn find_max_option_recursive(node: &Option<Box<TreeNode>>) -> Option<i32> {
match node {
None => [1],
Some(ref n) => {
if n.right.is_none() {
Some(n.[2])
} else {
find_max_option_recursive(&n.right)
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning Some(0) for empty tree.
Accessing right instead of val for node value.
✗ Incorrect
Return None if the tree is empty. Otherwise, return Some of the node's value when no right child exists.
5fill in blank
hardFill all three blanks to implement an iterative function that returns the maximum value or None if empty.
DSA Rust
fn find_max_iterative(node: &Option<Box<TreeNode>>) -> Option<i32> {
let mut current = node;
while let Some(ref n) = current {
if n.[1].is_none() {
return Some(n.[2]);
}
current = &n.[3];
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Using left child instead of right child.
Returning right child instead of val.
✗ Incorrect
Check if right child is None to find max, return node's val, and move to right child in loop.
