From 19edbde2988783f84f1e1d23242241f1d20d5dcd Mon Sep 17 00:00:00 2001 From: sgoudham Date: Fri, 18 Feb 2022 18:36:52 +0000 Subject: [PATCH] Implement recursive min/max --- src/lib.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 50dc32f..f3b3ea3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -169,7 +169,19 @@ impl Node { Err(()) } - // TODO -> Implement min(), max(), height(), is_valid(), invert() functions + fn min(&self) -> Option<&T> { + match &self.left { + None => Some(&self.value), + Some(node) => node.min(), + } + } + + fn max(&self) -> Option<&T> { + match &self.right { + None => Some(&self.value), + Some(node) => node.max(), + } + } fn extract_min(root: &mut HeapNode) -> T { if root.as_ref().unwrap().left.is_some() { @@ -294,6 +306,20 @@ impl BinarySearchTree { } } + pub fn min(&self) -> Option<&T> { + match self.root { + None => None, + Some(ref node) => node.min(), + } + } + + pub fn max(&self) -> Option<&T> { + match self.root { + None => None, + Some(ref node) => node.max(), + } + } + pub fn pre_order(&self) -> Vec<&T> { let mut elements: Vec<&T> = Vec::new(); Node::pre_order_vec(&self.root, &mut elements); @@ -528,6 +554,32 @@ mod bst_test { assert_eq!(actual_bst, expected_bst); } + #[test] + fn get_min_from_bst() { + let mut bst = BinarySearchTree::empty(); + assert_eq!(bst.min(), None); + + bst.insert(5); + bst.insert(3); + bst.insert(1); + bst.insert(15); + + assert_eq!(bst.min(), Some(&1)); + } + + #[test] + fn get_max_from_bst() { + let mut bst = BinarySearchTree::empty(); + assert_eq!(bst.max(), None); + + bst.insert(5); + bst.insert(12); + bst.insert(1); + bst.insert(15); + + assert_eq!(bst.max(), Some(&15)); + } + #[test] fn pre_order_traversal() { let mut bst = BinarySearchTree::empty();