Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a value into the BST.
DSA Rust
fn insert(root: &mut Option<Box<TreeNode>>, val: i32) {
match root {
None => *root = Some(Box::new(TreeNode { val, left: None, right: None })),
Some(node) => {
if val < node.val {
insert(&mut node.left, [1]);
} else {
insert(&mut node.right, val);
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing node.val instead of val causes incorrect insertion.
Modifying val before passing leads to wrong tree structure.
✗ Incorrect
We need to insert the exact value 'val' into the left subtree if it is less than the current node's value.
2fill in blank
mediumComplete the code to perform in-order traversal and collect node values.
DSA Rust
fn inorder(root: &Option<Box<TreeNode>>, vals: &mut Vec<i32>) {
if let Some(node) = root {
inorder(&node.left, vals);
vals.push([1]);
inorder(&node.right, vals);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.left.val causes error if left is None.
Using vals.len() is unrelated to node values.
✗ Incorrect
We push the current node's value during in-order traversal.
3fill in blank
hardFix the error in the two_sum function to check if the complement exists.
DSA Rust
fn two_sum(vals: &Vec<i32>, target: i32) -> bool {
let mut left = 0;
let mut right = vals.len() - 1;
while left < right {
let sum = vals[left] + vals[right];
if sum == target {
return true;
} else if sum < target {
left += [1];
} else {
right -= 1;
}
}
false
}Attempts:
3 left
💡 Hint
Common Mistakes
Incrementing by 0 causes infinite loop.
Using left or right as increment value causes type errors.
✗ Incorrect
We need to increment left by 1 to move forward when sum is less than target.
4fill in blank
hardFill both blanks to create a function that returns true if two numbers sum to target in BST.
DSA Rust
fn find_target(root: &Option<Box<TreeNode>>, target: i32) -> bool {
let mut vals = Vec::new();
[1](&root, &mut vals);
[2](&vals, target)
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling insert or search instead of inorder or two_sum.
Mixing order of function calls.
✗ Incorrect
We first collect values with inorder traversal, then check pairs with two_sum.
5fill in blank
hardFill all three blanks to complete the TreeNode struct and implement find_target.
DSA Rust
#[derive(Debug)] struct TreeNode { val: i32, [1]: Option<Box<TreeNode>>, [2]: Option<Box<TreeNode>>, } fn find_target(root: &Option<Box<TreeNode>>, target: i32) -> bool { let mut vals = Vec::new(); [3](&root, &mut vals); two_sum(&vals, target) }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'val' as a child field name.
Calling wrong function instead of inorder.
✗ Incorrect
TreeNode has left and right children; inorder collects values for two_sum.
