Given a Binary Search Tree (BST), what is the output of the inorder predecessor function when called on the node with value 15?
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
fn inorder_predecessor(root: &Option<Box<TreeNode>>, key: i32) -> Option<i32> {
let mut predecessor = None;
let mut current = root;
while let Some(node) = current {
if key <= node.val {
current = &node.left;
} else {
predecessor = Some(node.val);
current = &node.right;
}
}
predecessor
}
fn main() {
let root = Some(Box::new(TreeNode {
val: 20,
left: Some(Box::new(TreeNode {
val: 10,
left: Some(Box::new(TreeNode { val: 5, left: None, right: None })),
right: Some(Box::new(TreeNode { val: 15, left: None, right: None })),
})),
right: Some(Box::new(TreeNode {
val: 30,
left: None,
right: None,
})),
}));
let pred = inorder_predecessor(&root, 15);
println!("{:?}", pred);
}Inorder predecessor is the largest value smaller than the given key.
The inorder predecessor of 15 in the BST is 10 because 10 is the largest value less than 15.
Which statement correctly describes the inorder predecessor of a node in a BST?
Think about the inorder traversal order.
The inorder predecessor is the node that comes immediately before the given node in inorder traversal, which means it has the largest value smaller than the node.
What error will occur when running the following Rust code to find the inorder predecessor?
fn inorder_predecessor(root: &Option<Box<TreeNode>>, key: i32) -> Option<i32> {
let mut predecessor = None;
let mut current = root;
while let Some(node) = current {
if key < node.val {
current = &node.left;
} else {
predecessor = Some(node.val);
current = &node.right;
}
}
predecessor
}Check the condition for moving left or right in the loop.
The condition uses key < node.val instead of key <= node.val, so when key equals node.val, it incorrectly moves right, causing wrong predecessor.
Which option contains the correct Rust syntax to define a BST node struct with optional left and right children?
Children must be optional and boxed to allow recursive types.
Option B correctly uses Option to allow nullable recursive pointers.
Given the BST below, what is the inorder predecessor of the node with value 25?
BST structure:
- Root: 20
- Left subtree: 10 (left: 5, right: 15)
- Right subtree: 30 (left: 25, right: 35)
Inorder predecessor is the largest value smaller than the node's value.
The inorder predecessor of 25 is 20 because 20 is the largest value smaller than 25 in the BST.
