1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-23 09:16:44 +02:00

Use a type alias in binary tree exercise (#1589)

As suggested by @marshallpierce and @hurryabit
This commit is contained in:
Dustin J. Mitchell
2023-12-13 14:53:35 -05:00
committed by GitHub
parent c6973018c6
commit afea94b1ed
2 changed files with 45 additions and 14 deletions

View File

@ -16,34 +16,55 @@
use std::cmp::Ordering;
// ANCHOR: types
/// A node in the binary tree.
#[derive(Debug)]
struct BinaryTreeNode<T: Ord + Copy> {
struct Node<T: Ord + Copy> {
value: T,
left: BinaryTree<T>,
right: BinaryTree<T>,
left: Subtree<T>,
right: Subtree<T>,
}
/// A possibly-empty subtree.
#[derive(Debug)]
struct Subtree<T: Ord + Copy>(Option<Box<Node<T>>>);
/// 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<T: Ord + Copy>(Option<Box<BinaryTreeNode<T>>>);
pub struct BinaryTree<T: Ord + Copy> {
root: Subtree<T>,
}
// ANCHOR_END: types
impl<T: Ord + Copy> BinaryTree<T> {
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<T: Ord + Copy> Subtree<T> {
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<T: Ord + Copy> BinaryTree<T> {
}
}
impl<T: Ord + Copy> Node<T> {
fn new(value: T) -> Self {
Self {
value,
left: Subtree::new(),
right: Subtree::new(),
}
}
}
fn main() {
let mut tree = BinaryTree::new();
tree.insert("foo");