From cdfe0d44a396baf76ad38cbbd86fbb5f933996e3 Mon Sep 17 00:00:00 2001 From: sgoudham Date: Wed, 16 Feb 2022 01:39:41 +0000 Subject: [PATCH] Simplify Iterator(s) for BST --- src/ds.rs | 60 +++++++++++++++---------------------------------------- 1 file changed, 16 insertions(+), 44 deletions(-) diff --git a/src/ds.rs b/src/ds.rs index de11e58..d4e43ac 100644 --- a/src/ds.rs +++ b/src/ds.rs @@ -1,12 +1,8 @@ use std::cmp::Ordering; -use std::collections::VecDeque; +use std::vec::IntoIter; type Child = Option>>; -pub struct IntoPreOrderIter(T); -pub struct IntoInOrderIter(T); -pub struct IntoPostOrderIter(T); - #[derive(Debug)] pub struct BST { root: Child, @@ -84,27 +80,27 @@ impl Node { } } - fn pre_order_traversal(node: Child, pre_order: &mut VecDeque) { + fn pre_order_traversal(node: Child, pre_order: &mut Vec) { if let Some(node) = node { - pre_order.push_front(node.value); + pre_order.push(node.value); Self::pre_order_traversal(node.left, pre_order); Self::pre_order_traversal(node.right, pre_order); } } - fn in_order_traversal(node: Child, in_order: &mut VecDeque) { + fn in_order_traversal(node: Child, in_order: &mut Vec) { if let Some(node) = node { Self::in_order_traversal(node.left, in_order); - in_order.push_front(node.value); + in_order.push(node.value); Self::in_order_traversal(node.right, in_order); } } - fn post_order_traversal(node: Child, post_order: &mut VecDeque) { + fn post_order_traversal(node: Child, post_order: &mut Vec) { if let Some(node) = node { Self::post_order_traversal(node.left, post_order); Self::post_order_traversal(node.right, post_order); - post_order.push_front(node.value); + post_order.push(node.value); } } } @@ -148,46 +144,22 @@ impl BST { } } - pub fn into_pre_order_iter(self) -> IntoPreOrderIter> { - let mut pre_order = VecDeque::new(); + pub fn into_pre_order_iter(self) -> IntoIter { + let mut pre_order = Vec::new(); Node::pre_order_traversal(self.root, &mut pre_order); - IntoPreOrderIter(pre_order) + pre_order.into_iter() } - pub fn into_in_order_iter(self) -> IntoInOrderIter> { - let mut in_order = VecDeque::new(); + pub fn into_in_order_iter(self) -> IntoIter { + let mut in_order = Vec::new(); Node::in_order_traversal(self.root, &mut in_order); - IntoInOrderIter(in_order) + in_order.into_iter() } - pub fn into_post_order_iter(self) -> IntoPostOrderIter> { - let mut post_order = VecDeque::new(); + pub fn into_post_order_iter(self) -> IntoIter { + let mut post_order = Vec::new(); Node::post_order_traversal(self.root, &mut post_order); - IntoPostOrderIter(post_order) - } -} - -impl Iterator for IntoPreOrderIter> { - type Item = T; - - fn next(&mut self) -> Option { - self.0.pop_back() - } -} - -impl Iterator for IntoInOrderIter> { - type Item = T; - - fn next(&mut self) -> Option { - self.0.pop_back() - } -} - -impl Iterator for IntoPostOrderIter> { - type Item = T; - - fn next(&mut self) -> Option { - self.0.pop_back() + post_order.into_iter() } }