Which of the following best explains the main advantage of a Binary Search Tree (BST) over a plain Binary Tree?
Think about how the order of elements affects searching speed.
A Binary Search Tree keeps its elements in sorted order, which allows operations like search, insert, and delete to be done efficiently, usually in O(log n) time. A plain Binary Tree has no order, so these operations can take longer, often O(n).
Consider the following Rust-like pseudocode for searching a value in a tree. What is the output when searching for 7?
enum TreeNode {
Empty,
Node(i32, Box<TreeNode>, Box<TreeNode>),
}
fn search_bst(node: &TreeNode, val: i32) -> bool {
match node {
TreeNode::Empty => false,
TreeNode::Node(v, left, right) => {
if *v == val {
true
} else if val < *v {
search_bst(left, val)
} else {
search_bst(right, val)
}
}
}
}
fn search_plain(node: &TreeNode, val: i32) -> bool {
match node {
TreeNode::Empty => false,
TreeNode::Node(v, left, right) => {
if *v == val {
true
} else {
search_plain(left, val) || search_plain(right, val)
}
}
}
}
// Tree structure for BST:
// 5
// / \
// 3 8
// / \
// 7 10
// Tree structure for plain binary tree:
// 5
// / \
// 8 3
// / \
// 7 10
// What is the output of search_bst(root_bst, 7) and search_plain(root_plain, 7)?Both trees contain the value 7, but their structure differs.
Both search functions correctly find 7 in their respective trees. The BST search uses ordering to decide which branch to search, while the plain tree search checks both branches recursively.
Examine the Rust-like code below for inserting a value into a BST. What is the main reason it fails to maintain BST properties?
fn insert_bst(node: &mut TreeNode, val: i32) {
match node {
TreeNode::Empty => {
*node = TreeNode::Node(val, Box::new(TreeNode::Empty), Box::new(TreeNode::Empty));
}
TreeNode::Node(v, left, right) => {
if val <= *v {
insert_bst(left, val); // <-- Problem here
} else {
insert_bst(right, val);
}
}
}
}Check which subtree the code inserts smaller and larger values into.
In a BST, smaller or equal values go to the left subtree, larger values to the right. This code swaps them, breaking the BST property.
Which option correctly fixes the syntax error in the following Rust-like code for inorder traversal of a BST?
fn inorder(node: &TreeNode) {
match node {
TreeNode::Empty => (),
TreeNode::Node(v, left, right) => {
inorder(left);
println!("{}", v);
inorder(right);
}
}
}Rust requires statements to end with semicolons unless they are the last expression.
Missing semicolons after function calls cause syntax errors. Adding them fixes the code.
Consider a perfectly balanced Binary Search Tree of height 3 (root at height 1). How many nodes does it contain?
Recall the formula for the number of nodes in a perfect binary tree: 2^height - 1.
A perfectly balanced binary tree of height h has 2^h - 1 nodes. For height 3, nodes = 2^3 - 1 = 7.
