Created
April 2, 2021 12:22
-
-
Save Drup/897bd521fc6a71fa360a742e81699db8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::Ordering; | |
enum Tree<T: Ord> { | |
Node {v: T, left: Box<Tree<T>>, right: Box<Tree<T>>}, | |
Empty, | |
} | |
impl<T: Ord> Tree<T> { | |
fn find(&self, target: T) -> bool { | |
match self { | |
&Tree::Node { v, ref left, ref right } => { | |
if target == v { true } | |
else if target < v { right.find(target) } | |
else { left.find(target) } | |
}, | |
&Tree::Empty => false, | |
} | |
} | |
fn empty() -> Tree<T> { | |
Tree::Empty | |
} | |
fn insert(&mut self, nv: T) { | |
match self { | |
&mut Tree::Node { ref v, ref mut left, ref mut right } => { | |
match nv.cmp(v) { | |
Ordering::Less => right.insert(nv), | |
Ordering::Greater => left.insert(nv), | |
Ordering::Equal => return | |
} | |
}, | |
&mut Tree::Empty => { | |
*self = Tree::Node { | |
v: nv, | |
left: Box::new(Tree::Empty), | |
right: Box::new(Tree::Empty) | |
} | |
}, | |
}; | |
} | |
fn is_empty(&self) -> bool { | |
match self { | |
&Tree::Node { .. } => false, | |
&Tree::Empty => true, | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment