Skip to content

Instantly share code, notes, and snippets.

@et4te
Created September 22, 2017 19:55
Show Gist options
  • Save et4te/9a027e888996a1793549ebb6498b2e25 to your computer and use it in GitHub Desktop.
Save et4te/9a027e888996a1793549ebb6498b2e25 to your computer and use it in GitHub Desktop.
#[derive(Debug)]
enum BinaryTree<T: Ord> {
Leaf {
lhs: Box<BinaryTree<T>>,
rhs: Box<BinaryTree<T>>,
val: (T, Value),
},
Empty,
}
impl<T: Ord> BinaryTree<T> {
pub fn new() -> BinaryTree<T> {
BinaryTree::Empty
}
pub fn insert(&mut self, key: T, new_val: Value) {
match self {
&mut BinaryTree::Leaf { ref mut lhs, ref mut rhs, ref val } => {
match key.cmp(&val.0) {
Ordering::Greater =>
lhs.insert(key, new_val),
Ordering::Less =>
rhs.insert(key, new_val),
_ => return
}
},
&mut BinaryTree::Empty => {
*self = BinaryTree::Leaf {
lhs: Box::new(BinaryTree::Empty),
rhs: Box::new(BinaryTree::Empty),
val: (key, new_val),
}
}
}
}
pub fn is_empty(&self) -> bool {
match self {
&BinaryTree::Leaf { .. } =>
false,
&BinaryTree::Empty =>
true,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment