struct Node {
val: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn find_min(&self) -> i32 {
match &self.left {
Some(left_node) => left_node.find_min(),
None => self.val,
}
}
}
fn main() {
let bst = Node {
val: 10,
left: Some(Box::new(Node {
val: 5,
left: Some(Box::new(Node { val: 2, left: None, right: None })),
right: None,
})),
right: Some(Box::new(Node { val: 15, left: None, right: None })),
};
println!("{}", bst.find_min());
}The code recursively goes to the left child until it finds a node with no left child. That node's value is the minimum.
Here, the leftmost node has value 2.
struct Node {
val: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn find_min(&self) -> i32 {
match &self.left {
Some(left_node) => left_node.find_min(),
None => self.val,
}
}
}
fn main() {
let bst = Node {
val: 42,
left: None,
right: None,
};
println!("{}", bst.find_min());
}Since the BST has only one node with value 42 and no left child, find_min() returns 42.
struct Node {
val: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn find_min(&self) -> i32 {
if self.left.is_some() {
self.left.as_ref().unwrap().find_min()
} else {
self.val
}
}
}
fn main() {
let bst = Node {
val: 10,
left: Some(Box::new(Node {
val: 5,
left: None,
right: None,
})),
right: None,
};
println!("{}", bst.find_min());
}The code produces a compilation error. In the &self method, self.left has type &Option<Box<Node>>. The unwrap() method requires ownership (self: Option<T>) to consume the Option and move out the Box<Node>, which cannot be done on a borrow.
To fix, use match &self.left { Some(left_node) => left_node.find_min(), None => self.val } or self.left.as_ref().unwrap().find_min().
struct Node {
val: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn find_min(&self) -> i32 {
match &self.left {
Some(left_node) => left_node.find_min(),
None => self.val,
}
}
}
fn main() {
let bst = Node {
val: 20,
left: Some(Box::new(Node {
val: 10,
left: Some(Box::new(Node {
val: 5,
left: Some(Box::new(Node { val: 2, left: None, right: None })),
right: None,
})),
right: None,
})),
right: None,
};
println!("{}", bst.find_min());
}The find_min() function visits nodes 20, 10, 5, and 2 in order, totaling 4 nodes.
By definition, in a BST, all nodes in the left subtree have smaller values than the parent node. Recursively, the leftmost node has no left child and is the smallest.
