Add tests and fix find bug.

This commit is contained in:
Jesse Brault 2024-11-22 17:41:54 -06:00
parent 91ab5ced3c
commit e0287c4fce

View File

@ -33,8 +33,8 @@ impl<T: Ord> BinarySearchTree<T> {
} }
} }
pub fn find(&mut self, data: T) -> Option<T> { pub fn find(&self, data: T) -> Option<T> {
self.root.take().map(|mut root| root.find(data))? self.root.as_ref().map(|root| root.find(data))?
} }
} }
@ -66,11 +66,43 @@ impl<T: Ord> Node<T> {
} }
} }
fn find(&mut self, data: T) -> Option<T> { fn find(&self, data: T) -> Option<T> {
match self.data.cmp(&data) { match self.data.cmp(&data) {
Less => self.right.take().map(|mut right| right.find(data))?, Less => self.right.as_ref().map(|right| right.find(data))?,
Equal => Some(data), Equal => Some(data),
Greater => self.left.take().map(|mut left| left.find(data))?, Greater => self.left.as_ref().map(|left| left.find(data))?,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_and_find() {
let mut tree = BinarySearchTree::new();
tree.insert(1);
assert_eq!(tree.find(1), Some(1));
}
#[test]
fn insert_three_values_find_third() {
let mut tree = BinarySearchTree::new();
for num in [1, 2, 3] {
tree.insert(num);
}
assert_eq!(tree.find(3), Some(3));
}
#[test]
fn multiple_finds() {
let mut tree = BinarySearchTree::new();
for num in [1, 2, 3] {
tree.insert(num);
}
for num in [1, 2, 3] {
assert_eq!(tree.find(num), Some(num));
} }
} }
} }