Add binary_tee example

This commit is contained in:
Timothy Warren 2019-03-07 10:25:59 -05:00
parent b428ce3d10
commit d4b3bb172a
2 changed files with 53 additions and 0 deletions

7
bin_tree/Cargo.toml Normal file
View File

@ -0,0 +1,7 @@
[package]
name = "bin_tree"
version = "0.1.0"
authors = ["Timothy Warren <twarren@nabancard.com>"]
edition = "2018"
[dependencies]

46
bin_tree/src/main.rs Normal file
View File

@ -0,0 +1,46 @@
#[derive(Debug)]
enum BinaryTree<T> {
Empty,
NonEmpty(Box<TreeNode<T>>)
}
#[derive(Debug)]
struct TreeNode<T> {
element: T,
left: BinaryTree<T>,
right: BinaryTree<T>
}
impl<T: Ord> BinaryTree<T> {
fn add(&mut self, value: T) {
match *self {
BinaryTree::Empty => *self = BinaryTree::NonEmpty(Box::new(TreeNode {
element: value,
left: BinaryTree::Empty,
right: BinaryTree::Empty,
})),
BinaryTree::NonEmpty(ref mut node) => {
if value <= node.element {
node.left.add(value);
} else {
node.right.add(value);
}
}
}
}
}
fn main() {
let mut tree = BinaryTree::Empty;
tree.add("Mercury");
tree.add("Venus");
tree.add("Earth");
tree.add("Mars");
tree.add("Jupiter");
tree.add("Saturn");
tree.add("Uranus");
tree.add("Neptune");
tree.add("Pluto");
println!("Tree: {:?}", tree);
}