Consider the following Rust code that builds a binary search tree (BST) and searches for the value 7.
struct Node {
val: i32,
left: Option>,
right: Option>,
}
impl Node {
fn new(val: i32) -> Self {
Node { val, left: None, right: None }
}
fn insert(&mut self, val: i32) {
if val < self.val {
match &mut self.left {
Some(left_node) => left_node.insert(val),
None => self.left = Some(Box::new(Node::new(val))),
}
} else if val > self.val {
match &mut self.right {
Some(right_node) => right_node.insert(val),
None => self.right = Some(Box::new(Node::new(val))),
}
}
}
fn search(&self, val: i32) -> bool {
if val == self.val {
true
} else if val < self.val {
match &self.left {
Some(left_node) => left_node.search(val),
None => false,
}
} else {
match &self.right {
Some(right_node) => right_node.search(val),
None => false,
}
}
}
}
fn main() {
let mut root = Node::new(10);
root.insert(5);
root.insert(15);
root.insert(3);
root.insert(7);
root.insert(12);
root.insert(18);
println!("{}", root.search(7));
} Think about whether the value 7 was inserted into the tree before searching.
The value 7 was inserted into the BST, so searching for 7 returns true.
Using the same BST as before, what will be the output of searching for the value 6?
fn main() {
let mut root = Node::new(10);
root.insert(5);
root.insert(15);
root.insert(3);
root.insert(7);
root.insert(12);
root.insert(18);
println!("{}", root.search(6));
}Check if 6 was inserted into the tree before searching.
The value 6 was never inserted, so searching returns false.
Consider this Rust code snippet for BST search. What error does it produce when compiled?
fn search(&self, val: i32) -> bool {
if val == self.val {
true
} else if val < self.val {
if let Some(left_node) = &self.left {
left_node.search(val)
} else {
false
}
} else {
if let Some(right_node) = &self.right {
right_node.search(val)
} else {
false
}
}
}Check if all branches return a boolean value.
The last else branch does not return a value if right is None, causing a missing return error.
Given the BST constructed by inserting 10, 5, 15, 3, 7, 12, 18 in that order, how many nodes are visited during a search for 12?
Trace the path from root to the node with value 12.
Nodes visited: 10 (root), 15 (right child), 12 (left child of 15) → total 3 nodes.
Consider this Rust code snippet:
fn main() {
let mut root = Node::new(10);
root.insert(5);
root.insert(15);
root.insert(3);
root.insert(7);
root.insert(12);
root.insert(18);
let found = root.search(20);
println!("{}", found);
}What will be printed?
Was 20 inserted into the BST before searching?
20 was never inserted, so search returns false.
