Implement height() and WIP level order traversal

pull/3/head
sgoudham 3 years ago
parent 06307105e0
commit e96bdbebbf
Signed by: hammy
GPG Key ID: 44E818FD5457EEA4

@ -1,5 +1,4 @@
//! This crate contains Recursive & Iterative Binary Search Tree Implementations. All common //! This crate contains Recursive & Iterative Binary Search Tree Implementations. All common operations are included along with common traversal iterators.
//! operations are included along with common traversal iterators.
//! //!
//! All elements within the Binary Search Trees _must_ implement the [Ord] trait. //! All elements within the Binary Search Trees _must_ implement the [Ord] trait.
//! //!
@ -81,7 +80,8 @@
//! assert_ne!(recursive_bst, RecursiveBST::new()); //! assert_ne!(recursive_bst, RecursiveBST::new());
//! ``` //! ```
use std::cmp::Ordering; use std::cmp::{max, Ordering};
use std::collections::VecDeque;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
use std::vec::IntoIter; use std::vec::IntoIter;
@ -113,6 +113,16 @@ use std::vec::IntoIter;
/// assert_eq!(bst_from_vec.in_order_vec(), vec![&2, &5, &10, &15, &18]); /// assert_eq!(bst_from_vec.in_order_vec(), vec![&2, &5, &10, &15, &18]);
/// assert_eq!(bst_from_vec.sorted_vec(), vec![&2, &5, &10, &15, &18]); /// assert_eq!(bst_from_vec.sorted_vec(), vec![&2, &5, &10, &15, &18]);
pub trait BinarySearchTree<T: Ord> { pub trait BinarySearchTree<T: Ord> {
/// Create an empty Binary Search Tree
///
/// No nodes are allocated on the heap yet
///
/// # Examples
///
/// ```rust
/// use bst_rs::IterativeBST;
///
/// let mut bst = IterativeBST::new();
fn new() -> Self; fn new() -> Self;
fn size(&self) -> usize; fn size(&self) -> usize;
fn is_empty(&self) -> bool; fn is_empty(&self) -> bool;
@ -122,6 +132,7 @@ pub trait BinarySearchTree<T: Ord> {
fn remove(&mut self, value: &T); fn remove(&mut self, value: &T);
fn retrieve(&self, value: &T) -> Option<&T>; fn retrieve(&self, value: &T) -> Option<&T>;
fn retrieve_as_mut(&mut self, value: &T) -> Option<&mut T>; fn retrieve_as_mut(&mut self, value: &T) -> Option<&mut T>;
fn height(&self) -> usize;
fn min(&self) -> Option<&T>; fn min(&self) -> Option<&T>;
fn max(&self) -> Option<&T>; fn max(&self) -> Option<&T>;
fn remove_min(&mut self) -> Option<T>; fn remove_min(&mut self) -> Option<T>;
@ -131,12 +142,15 @@ pub trait BinarySearchTree<T: Ord> {
fn pre_order_vec(&self) -> Vec<&T>; fn pre_order_vec(&self) -> Vec<&T>;
fn in_order_vec(&self) -> Vec<&T>; fn in_order_vec(&self) -> Vec<&T>;
fn post_order_vec(&self) -> Vec<&T>; fn post_order_vec(&self) -> Vec<&T>;
fn level_order_vec(&self) -> Vec<&T>;
fn pre_order_iter(&self) -> IntoIter<&T>; fn pre_order_iter(&self) -> IntoIter<&T>;
fn in_order_iter(&self) -> IntoIter<&T>; fn in_order_iter(&self) -> IntoIter<&T>;
fn post_order_iter(&self) -> IntoIter<&T>; fn post_order_iter(&self) -> IntoIter<&T>;
fn level_order_iter(&self) -> IntoIter<&T>;
fn into_pre_order_iter(self) -> IntoIter<T>; fn into_pre_order_iter(self) -> IntoIter<T>;
fn into_in_order_iter(self) -> IntoIter<T>; fn into_in_order_iter(self) -> IntoIter<T>;
fn into_post_order_iter(self) -> IntoIter<T>; fn into_post_order_iter(self) -> IntoIter<T>;
fn into_level_order_iter(self) -> IntoIter<T>;
} }
type HeapNode<T> = Option<Box<Node<T>>>; type HeapNode<T> = Option<Box<Node<T>>>;
@ -324,6 +338,13 @@ impl<T: Ord> BinarySearchTree<T> for IterativeBST<T> {
Node::iterative_retrieve_as_mut(&mut self.root, value) Node::iterative_retrieve_as_mut(&mut self.root, value)
} }
fn height(&self) -> usize {
match self.root {
None => 0,
Some(_) => Node::iterative_height(&self.root),
}
}
fn min(&self) -> Option<&T> { fn min(&self) -> Option<&T> {
Node::iterative_min(&self.root) Node::iterative_min(&self.root)
} }
@ -368,6 +389,10 @@ impl<T: Ord> BinarySearchTree<T> for IterativeBST<T> {
Node::iterative_post_order_vec(&self.root) Node::iterative_post_order_vec(&self.root)
} }
fn level_order_vec(&self) -> Vec<&T> {
Node::iterative_level_order_vec(&self.root)
}
fn pre_order_iter(&self) -> IntoIter<&T> { fn pre_order_iter(&self) -> IntoIter<&T> {
Node::iterative_pre_order_vec(&self.root).into_iter() Node::iterative_pre_order_vec(&self.root).into_iter()
} }
@ -380,6 +405,10 @@ impl<T: Ord> BinarySearchTree<T> for IterativeBST<T> {
Node::iterative_post_order_vec(&self.root).into_iter() Node::iterative_post_order_vec(&self.root).into_iter()
} }
fn level_order_iter(&self) -> IntoIter<&T> {
Node::iterative_level_order_vec(&self.root).into_iter()
}
fn into_pre_order_iter(self) -> IntoIter<T> { fn into_pre_order_iter(self) -> IntoIter<T> {
Node::iterative_consume_pre_order_vec(self.root).into_iter() Node::iterative_consume_pre_order_vec(self.root).into_iter()
} }
@ -391,6 +420,10 @@ impl<T: Ord> BinarySearchTree<T> for IterativeBST<T> {
fn into_post_order_iter(self) -> IntoIter<T> { fn into_post_order_iter(self) -> IntoIter<T> {
Node::iterative_consume_post_order_vec(self.root).into_iter() Node::iterative_consume_post_order_vec(self.root).into_iter()
} }
fn into_level_order_iter(self) -> IntoIter<T> {
Node::iterative_consume_level_order_vec(self.root).into_iter()
}
} }
impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> { impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> {
@ -454,6 +487,13 @@ impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> {
} }
} }
fn height(&self) -> usize {
match self.root {
None => 0,
Some(_) => Node::recursive_height(&self.root),
}
}
fn min(&self) -> Option<&T> { fn min(&self) -> Option<&T> {
match self.root { match self.root {
None => None, None => None,
@ -524,6 +564,12 @@ impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> {
elements elements
} }
fn level_order_vec(&self) -> Vec<&T> {
let mut elements: Vec<&T> = Vec::new();
Node::recursive_level_order_vec(&self.root, &mut elements);
elements
}
fn pre_order_iter(&self) -> IntoIter<&T> { fn pre_order_iter(&self) -> IntoIter<&T> {
let mut elements: Vec<&T> = Vec::new(); let mut elements: Vec<&T> = Vec::new();
Node::recursive_pre_order_vec(&self.root, &mut elements); Node::recursive_pre_order_vec(&self.root, &mut elements);
@ -542,6 +588,12 @@ impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> {
elements.into_iter() elements.into_iter()
} }
fn level_order_iter(&self) -> IntoIter<&T> {
let mut elements: Vec<&T> = Vec::new();
Node::recursive_level_order_vec(&self.root, &mut elements);
elements.into_iter()
}
fn into_pre_order_iter(self) -> IntoIter<T> { fn into_pre_order_iter(self) -> IntoIter<T> {
let mut elements = Vec::new(); let mut elements = Vec::new();
Node::recursive_consume_pre_order_vec(self.root, &mut elements); Node::recursive_consume_pre_order_vec(self.root, &mut elements);
@ -559,6 +611,12 @@ impl<T: Ord> BinarySearchTree<T> for RecursiveBST<T> {
Node::recursive_consume_post_order_vec(self.root, &mut elements); Node::recursive_consume_post_order_vec(self.root, &mut elements);
elements.into_iter() elements.into_iter()
} }
fn into_level_order_iter(self) -> IntoIter<T> {
let mut elements = Vec::new();
Node::recursive_consume_level_order_vec(self.root, &mut elements);
elements.into_iter()
}
} }
impl<T: Ord> Node<T> { impl<T: Ord> Node<T> {
@ -684,6 +742,41 @@ impl<T: Ord> Node<T> {
} }
} }
fn iterative_height(root: &HeapNode<T>) -> usize {
let mut height = 0;
let mut queue = VecDeque::new();
queue.push_front(root);
while !queue.is_empty() {
let mut size = queue.len();
while size > 0 {
let current = queue.pop_front().as_ref().unwrap().as_ref().unwrap();
if current.left.is_some() {
queue.push_back(&current.left);
}
if current.right.is_some() {
queue.push_back(&current.right);
}
size -= 1;
}
height += 1;
}
height
}
fn recursive_height(root: &HeapNode<T>) -> usize {
match root {
None => 0,
Some(node) => {
1 + max(
Node::recursive_height(&node.left),
Node::recursive_height(&node.right),
)
}
}
}
fn iterative_remove(mut root: &mut HeapNode<T>, value: &T) -> Result<(), ()> { fn iterative_remove(mut root: &mut HeapNode<T>, value: &T) -> Result<(), ()> {
while let Some(ref mut current) = root { while let Some(ref mut current) = root {
match value.cmp(&current.value) { match value.cmp(&current.value) {
@ -896,6 +989,52 @@ impl<T: Ord> Node<T> {
} }
} }
fn iterative_level_order_vec(root: &HeapNode<T>) -> Vec<&T> {
let mut elements = Vec::new();
let mut deque = VecDeque::new();
deque.push_front(root.as_ref());
while let Some(current) = deque.pop_front().unwrap_or(None) {
elements.push(&current.value);
if current.left.is_some() {
deque.push_back(current.left.as_ref());
}
if current.right.is_some() {
deque.push_back(current.right.as_ref());
}
}
elements
}
fn recursive_level_order_vec<'a>(root: &'a HeapNode<T>, elements: &mut Vec<&'a T>) {
let height = Node::recursive_height(root);
for i in 1..=height {
Node::recursive_current_level(root, elements, i);
}
}
fn recursive_current_level<'a>(root: &'a HeapNode<T>, elements: &mut Vec<&'a T>, level: usize) {
if root.is_some() {
match level.cmp(&1) {
Ordering::Less => {}
Ordering::Equal => elements.push(&root.as_ref().unwrap().value),
Ordering::Greater => {
Node::recursive_current_level(
&root.as_ref().unwrap().left,
elements,
level - 1,
);
Node::recursive_current_level(
&root.as_ref().unwrap().right,
elements,
level - 1,
);
}
}
}
}
fn iterative_consume_pre_order_vec(node: HeapNode<T>) -> Vec<T> { fn iterative_consume_pre_order_vec(node: HeapNode<T>) -> Vec<T> {
let mut elements = Vec::new(); let mut elements = Vec::new();
let mut stack = vec![node]; let mut stack = vec![node];
@ -979,4 +1118,44 @@ impl<T: Ord> Node<T> {
elements.push(node.value); elements.push(node.value);
} }
} }
fn iterative_consume_level_order_vec(root: HeapNode<T>) -> Vec<T> {
let mut elements = Vec::new();
let mut deque = VecDeque::new();
deque.push_front(root);
while let Some(current) = deque.pop_front().unwrap_or(None) {
elements.push(current.value);
if current.left.is_some() {
deque.push_back(current.left);
}
if current.right.is_some() {
deque.push_back(current.right);
}
}
elements
}
fn recursive_consume_level_order_vec(mut root: HeapNode<T>, elements: &mut Vec<T>) {
let height = Node::recursive_height(&root);
for i in 1..=height {
Node::recursive_consume_current_level(&mut root, elements, i);
}
}
fn recursive_consume_current_level(root: &mut HeapNode<T>, elements: &mut Vec<T>, level: usize) {
if let Some(..) = root {
match level.cmp(&1) {
Ordering::Less => {}
Ordering::Equal => elements.push(root.as_mut().unwrap().value),
Ordering::Greater => {
if let Some(node) = root {
Node::recursive_consume_current_level(&mut node.left, elements, level - 1);
Node::recursive_consume_current_level(&mut node.right, elements, level - 1);
}
}
}
}
}
} }

@ -1,6 +1,6 @@
use std::vec::IntoIter; use std::vec::IntoIter;
use bst_rs::{BinarySearchTree, IterativeBST}; use bst_rs::{BinarySearchTree, IterativeBST, RecursiveBST};
#[test] #[test]
fn successfully_insert_elements_into_bst() { fn successfully_insert_elements_into_bst() {
@ -192,6 +192,21 @@ fn successfully_retrieve_element_as_mut_and_modify_bst() {
assert_eq!(actual_bst, expected_bst); assert_eq!(actual_bst, expected_bst);
} }
#[test]
fn successfully_get_height_of_bst() {
let mut bst = IterativeBST::new();
assert_eq!(bst.height(), 0);
bst.insert(15);
bst.insert(10);
bst.insert(20);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
assert_eq!(bst.height(), 3);
}
#[test] #[test]
fn successfully_get_min_from_bst() { fn successfully_get_min_from_bst() {
let mut bst = IterativeBST::new(); let mut bst = IterativeBST::new();
@ -349,6 +364,43 @@ fn post_order_iter() {
assert_eq!(another_post_order_iter.next(), None); assert_eq!(another_post_order_iter.next(), None);
} }
#[test]
fn level_order_iter() {
let mut bst = IterativeBST::new();
bst.insert(15);
bst.insert(20);
bst.insert(10);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
let mut level_order_iter = bst.level_order_iter();
assert_eq!(level_order_iter.next(), Some(&15));
assert_eq!(level_order_iter.next(), Some(&10));
assert_eq!(level_order_iter.next(), Some(&20));
assert_eq!(level_order_iter.next(), Some(&8));
assert_eq!(level_order_iter.next(), Some(&12));
assert_eq!(level_order_iter.next(), Some(&16));
assert_eq!(level_order_iter.next(), Some(&25));
assert_eq!(level_order_iter.next(), None);
bst.insert(4);
let mut another_level_order_iter = bst.level_order_iter();
assert_eq!(another_level_order_iter.next(), Some(&15));
assert_eq!(another_level_order_iter.next(), Some(&10));
assert_eq!(another_level_order_iter.next(), Some(&20));
assert_eq!(another_level_order_iter.next(), Some(&8));
assert_eq!(another_level_order_iter.next(), Some(&12));
assert_eq!(another_level_order_iter.next(), Some(&16));
assert_eq!(another_level_order_iter.next(), Some(&25));
assert_eq!(another_level_order_iter.next(), Some(&4));
assert_eq!(another_level_order_iter.next(), None);
}
#[test] #[test]
fn into_pre_order_iter_with_no_elements() { fn into_pre_order_iter_with_no_elements() {
let bst: IterativeBST<i32> = IterativeBST::new(); let bst: IterativeBST<i32> = IterativeBST::new();
@ -473,6 +525,45 @@ fn into_post_order_iter_with_many_elements() {
assert_eq!(post_order_traversal.next(), None); assert_eq!(post_order_traversal.next(), None);
} }
#[test]
fn into_level_order_iter_with_no_elements() {
let bst: IterativeBST<i32> = IterativeBST::new();
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), None);
}
#[test]
fn into_level_order_iter_with_one_element() {
let mut bst = IterativeBST::new();
bst.insert(3);
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), Some(3));
assert_eq!(level_order_traversal.next(), None);
}
#[test]
fn into_level_order_iter_with_many_elements() {
let mut bst = IterativeBST::new();
bst.insert(3);
bst.insert(5);
bst.insert(4);
bst.insert(1);
bst.insert(2);
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), Some(3));
assert_eq!(level_order_traversal.next(), Some(1));
assert_eq!(level_order_traversal.next(), Some(5));
assert_eq!(level_order_traversal.next(), Some(2));
assert_eq!(level_order_traversal.next(), Some(4));
assert_eq!(level_order_traversal.next(), None);
}
#[test] #[test]
fn successfully_get_sorted_vec() { fn successfully_get_sorted_vec() {
let bst: IterativeBST<i32> = IterativeBST::new(); let bst: IterativeBST<i32> = IterativeBST::new();
@ -542,6 +633,22 @@ fn successfully_get_post_order_vec() {
assert_eq!(bst.post_order_vec(), vec![&2, &1, &5, &4, &3]); assert_eq!(bst.post_order_vec(), vec![&2, &1, &5, &4, &3]);
} }
#[test]
fn successfully_get_level_order_vec() {
let mut bst = IterativeBST::new();
assert!(bst.level_order_vec().is_empty());
bst.insert(15);
bst.insert(20);
bst.insert(10);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
assert_eq!(bst.level_order_vec(), vec![&15, &10, &20, &8, &12, &16, &25]);
}
#[test] #[test]
fn successfully_create_bst_from_vec() { fn successfully_create_bst_from_vec() {
let mut expected_bst = IterativeBST::new(); let mut expected_bst = IterativeBST::new();

@ -192,6 +192,21 @@ fn successfully_retrieve_element_as_mut_and_modify_bst() {
assert_eq!(actual_bst, expected_bst); assert_eq!(actual_bst, expected_bst);
} }
#[test]
fn successfully_get_height_of_bst() {
let mut bst = RecursiveBST::new();
assert_eq!(bst.height(), 0);
bst.insert(15);
bst.insert(10);
bst.insert(20);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
assert_eq!(bst.height(), 3);
}
#[test] #[test]
fn successfully_get_min_from_bst() { fn successfully_get_min_from_bst() {
let mut bst = RecursiveBST::new(); let mut bst = RecursiveBST::new();
@ -349,6 +364,43 @@ fn post_order_iter() {
assert_eq!(another_post_order_iter.next(), None); assert_eq!(another_post_order_iter.next(), None);
} }
#[test]
fn level_order_iter() {
let mut bst = RecursiveBST::new();
bst.insert(15);
bst.insert(20);
bst.insert(10);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
let mut level_order_iter = bst.level_order_iter();
assert_eq!(level_order_iter.next(), Some(&15));
assert_eq!(level_order_iter.next(), Some(&10));
assert_eq!(level_order_iter.next(), Some(&20));
assert_eq!(level_order_iter.next(), Some(&8));
assert_eq!(level_order_iter.next(), Some(&12));
assert_eq!(level_order_iter.next(), Some(&16));
assert_eq!(level_order_iter.next(), Some(&25));
assert_eq!(level_order_iter.next(), None);
bst.insert(4);
let mut another_level_order_iter = bst.level_order_iter();
assert_eq!(another_level_order_iter.next(), Some(&15));
assert_eq!(another_level_order_iter.next(), Some(&10));
assert_eq!(another_level_order_iter.next(), Some(&20));
assert_eq!(another_level_order_iter.next(), Some(&8));
assert_eq!(another_level_order_iter.next(), Some(&12));
assert_eq!(another_level_order_iter.next(), Some(&16));
assert_eq!(another_level_order_iter.next(), Some(&25));
assert_eq!(another_level_order_iter.next(), Some(&4));
assert_eq!(another_level_order_iter.next(), None);
}
#[test] #[test]
fn into_pre_order_iter_with_no_elements() { fn into_pre_order_iter_with_no_elements() {
let bst: RecursiveBST<i32> = RecursiveBST::new(); let bst: RecursiveBST<i32> = RecursiveBST::new();
@ -473,6 +525,45 @@ fn into_post_order_iter_with_many_elements() {
assert_eq!(post_order_traversal.next(), None); assert_eq!(post_order_traversal.next(), None);
} }
#[test]
fn into_level_order_iter_with_no_elements() {
let bst: RecursiveBST<i32> = RecursiveBST::new();
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), None);
}
#[test]
fn into_level_order_iter_with_one_element() {
let mut bst = RecursiveBST::new();
bst.insert(3);
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), Some(3));
assert_eq!(level_order_traversal.next(), None);
}
#[test]
fn into_level_order_iter_with_many_elements() {
let mut bst = RecursiveBST::new();
bst.insert(3);
bst.insert(5);
bst.insert(4);
bst.insert(1);
bst.insert(2);
let mut level_order_traversal = bst.into_level_order_iter();
assert_eq!(level_order_traversal.next(), Some(3));
assert_eq!(level_order_traversal.next(), Some(1));
assert_eq!(level_order_traversal.next(), Some(5));
assert_eq!(level_order_traversal.next(), Some(2));
assert_eq!(level_order_traversal.next(), Some(4));
assert_eq!(level_order_traversal.next(), None);
}
#[test] #[test]
fn successfully_get_sorted_vec() { fn successfully_get_sorted_vec() {
let bst: RecursiveBST<i32> = RecursiveBST::new(); let bst: RecursiveBST<i32> = RecursiveBST::new();
@ -542,6 +633,22 @@ fn successfully_get_post_order_vec() {
assert_eq!(bst.post_order_vec(), vec![&2, &1, &5, &4, &3]); assert_eq!(bst.post_order_vec(), vec![&2, &1, &5, &4, &3]);
} }
#[test]
fn successfully_get_level_order_vec() {
let mut bst = RecursiveBST::new();
assert!(bst.level_order_vec().is_empty());
bst.insert(15);
bst.insert(20);
bst.insert(10);
bst.insert(8);
bst.insert(12);
bst.insert(16);
bst.insert(25);
assert_eq!(bst.level_order_vec(), vec![&15, &10, &20, &8, &12, &16, &25]);
}
#[test] #[test]
fn successfully_create_bst_from_vec() { fn successfully_create_bst_from_vec() {
let mut expected_bst = RecursiveBST::new(); let mut expected_bst = RecursiveBST::new();

Loading…
Cancel
Save