Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a value into a Binary Search Tree (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 wrong insertion.
Modifying val before passing leads to incorrect tree structure.
✗ Incorrect
We insert the same value 'val' recursively into the left or right subtree depending on comparison.
2fill in blank
mediumComplete the code to search for a value in a BST.
DSA Rust
fn search(root: &Option<Box<TreeNode>>, val: i32) -> bool {
match root {
None => false,
Some(node) => {
if val == node.val {
true
} else if val [1] node.val {
search(&node.left, val)
} else {
search(&node.right, val)
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' reverses search direction.
Using '==' in the else-if causes logic errors.
✗ Incorrect
If val is less than node.val, search left subtree; else search right subtree.
3fill in blank
hardFix the error in the BST insertion code to maintain BST property.
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 [1] node.val {
insert(&mut node.right, val);
} else {
insert(&mut node.left, val);
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping left and right insertion breaks BST property.
Using equality in comparison causes incorrect placement.
✗ Incorrect
For BST insertion, values less than node.val go to left subtree.
4fill in blank
hardComplete the inorder traversal code. In a BST, inorder visits nodes in sorted order (unlike plain binary tree).
DSA Rust
fn inorder(root: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
match root {
None => (),
Some(node) => {
inorder(&node.[1], result);
result.push(node.val);
inorder(&node.[2], result);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Preorder (root-left-right) doesn't sort.
Postorder (left-right-root) doesn't sort.
✗ Incorrect
Inorder: left-root-right gives ascending order in BST due to ordering property.
5fill in blank
hardFill in the average time complexities for search to see why BST > plain binary tree.
DSA Rust
/* Average search time complexity in BST: [1] Average search time complexity in plain binary tree: [2] */
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting BST assumes balance/average case.
Assuming plain tree benefits from height alone.
✗ Incorrect
BST: O(log n) average due to sorted order enabling binary search. Plain binary tree: O(n) as no ordering.
