diff --git a/src/smart-pointers/exercise.md b/src/smart-pointers/exercise.md index bd87f4de..72bedcb7 100644 --- a/src/smart-pointers/exercise.md +++ b/src/smart-pointers/exercise.md @@ -11,6 +11,9 @@ nodes in N's right subtree will contain larger values. Implement the following types, so that the given tests pass. +Extra Credit: implement an iterator over a binary tree that returns the values +in order. + ```rust,editable {{#include exercise.rs:types}} @@ -18,6 +21,3 @@ Implement the following types, so that the given tests pass. {{#include exercise.rs:tests}} ``` - -Extra Credit: implement an iterator over a binary tree that returns the values -in order. diff --git a/src/smart-pointers/exercise.rs b/src/smart-pointers/exercise.rs index dc9e8cd3..a958b582 100644 --- a/src/smart-pointers/exercise.rs +++ b/src/smart-pointers/exercise.rs @@ -16,34 +16,55 @@ use std::cmp::Ordering; // ANCHOR: types +/// A node in the binary tree. #[derive(Debug)] -struct BinaryTreeNode { +struct Node { value: T, - left: BinaryTree, - right: BinaryTree, + left: Subtree, + right: Subtree, } +/// A possibly-empty subtree. +#[derive(Debug)] +struct Subtree(Option>>); + /// A container storing a set of values, using a binary tree. /// /// If the same value is added multiple times, it is only stored once. #[derive(Debug)] -pub struct BinaryTree(Option>>); +pub struct BinaryTree { + root: Subtree, +} // ANCHOR_END: types impl BinaryTree { + fn new() -> Self { + Self { + root: Subtree::new(), + } + } + + fn insert(&mut self, value: T) { + self.root.insert(value); + } + + fn has(&self, value: T) -> bool { + self.root.has(value) + } + + fn len(&self) -> usize { + self.root.len() + } +} + +impl Subtree { fn new() -> Self { Self(None) } fn insert(&mut self, value: T) { match &mut self.0 { - None => { - self.0 = Some(Box::new(BinaryTreeNode { - value, - left: BinaryTree::new(), - right: BinaryTree::new(), - })); - } + None => self.0 = Some(Box::new(Node::new(value))), Some(n) => match value.cmp(&n.value) { Ordering::Less => n.left.insert(value), Ordering::Equal => {} @@ -71,6 +92,16 @@ impl BinaryTree { } } +impl Node { + fn new(value: T) -> Self { + Self { + value, + left: Subtree::new(), + right: Subtree::new(), + } + } +} + fn main() { let mut tree = BinaryTree::new(); tree.insert("foo");