Add binary_tee example
This commit is contained in:
parent
b428ce3d10
commit
d4b3bb172a
7
bin_tree/Cargo.toml
Normal file
7
bin_tree/Cargo.toml
Normal 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
46
bin_tree/src/main.rs
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user