Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to perform an inorder traversal of the BST.
DSA Rust
fn inorder_traversal(root: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
if let Some(node) = root {
inorder_traversal(&node.left, result);
result.push(node.val);
[1](&node.right, result);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling a different traversal function on the right subtree.
Forgetting to recurse on the right subtree.
✗ Incorrect
The inorder traversal visits the left subtree, then the node, then the right subtree. The recursive call on the right subtree must use the same inorder_traversal function.
2fill in blank
mediumComplete the code to return the kth smallest element from the sorted list.
DSA Rust
fn kth_smallest(root: &Option<Box<TreeNode>>, k: usize) -> i32 {
let mut result = Vec::new();
inorder_traversal(root, &mut result);
[1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using k as the index directly causing out-of-bounds error.
Returning the first element instead of the kth.
✗ Incorrect
The vector is zero-indexed, so the kth smallest element is at index k-1.
3fill in blank
hardFix the error in the function signature to accept the BST root correctly.
DSA Rust
fn kth_smallest([1]: &Option<Box<TreeNode>>, k: usize) -> i32 { let mut result = Vec::new(); inorder_traversal(root, &mut result); result[k - 1] }
Attempts:
3 left
💡 Hint
Common Mistakes
Using owned Box causing move errors.
Using Option> without reference causing ownership issues.
✗ Incorrect
The function should accept a reference to an Option> to avoid ownership issues and allow recursion.
4fill in blank
hardFill both blanks to create a recursive function that returns the kth smallest element without extra space.
DSA Rust
fn kth_smallest_helper(root: &Option<Box<TreeNode>>, k: &mut i32, result: &mut Option<i32>) {
if let Some(node) = root {
kth_smallest_helper(&node.left, k, result);
*k -= 1;
if *k == [1] {
*result = Some(node.val);
return;
}
kth_smallest_helper([2], k, result);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if k equals 1 instead of 0.
Recursing on the left subtree again instead of right.
✗ Incorrect
When k reaches 0, we found the kth smallest element. The recursive call after checking the node should be on the right subtree.
5fill in blank
hardFill all three blanks to implement the main function using the helper to find the kth smallest element.
DSA Rust
fn kth_smallest(root: &Option<Box<TreeNode>>, k: i32) -> i32 {
let mut k_mut = [1];
let mut result = [2];
kth_smallest_helper(root, &mut k_mut, &mut result);
[3].unwrap()
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing k directly without making it mutable.
Initializing result with Some value instead of None.
Returning k instead of the result.
✗ Incorrect
We create a mutable copy of k, initialize result as None, call the helper, and unwrap the result to get the value.
