Skip to content

Instantly share code, notes, and snippets.

@cogas
Last active August 22, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cogas/a72d4dc7fc62348b9243272afb8df5d0 to your computer and use it in GitHub Desktop.
Save cogas/a72d4dc7fc62348b9243272afb8df5d0 to your computer and use it in GitHub Desktop.
純粋な二分木
use std::rc::Rc;
use std::convert::From;
#[derive(Debug, Clone)]
pub enum PureBTree<T: Ord+Clone> {
Empty,
Node(T, Rc<PureBTree<T>>, Rc<PureBTree<T>>)
}
impl<T: Ord+Clone> From<T> for PureBTree<T> {
fn from(x: T) -> Self {
PureBTree::Node(x, Rc::new(PureBTree::Empty), Rc::new(PureBTree::Empty))
}
}
impl<T: Ord+Clone> PureBTree<T> {
pub fn new() -> PureBTree<T> {
PureBTree::Empty
}
pub fn search(&self, needle: &T) -> bool {
match *self {
PureBTree::Empty => false,
PureBTree::Node(ref value, ref left, ref right) => {
if needle == value {
true
} else if needle < value {
left.search(needle)
} else if needle > value {
right.search(needle)
}
else {
unreachable!();
}
}
}
}
pub fn insert(&self, value: T) -> PureBTree<T> {
match *self {
PureBTree::Empty => PureBTree::from(value),
PureBTree::Node(ref x, ref left, ref right) => {
if value < *x {
PureBTree::Node(x.clone(), Rc::new(left.insert(value)), right.clone())
} else if value > *x {
PureBTree::Node(x.clone(), left.clone(), Rc::new(right.insert(value)))
} else {
self.clone()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment