Skip to content

Instantly share code, notes, and snippets.

Created September 1, 2016 12:38
Show Gist options
  • Save anonymous/7216b276410e84db3be86c1647d6f856 to your computer and use it in GitHub Desktop.
Save anonymous/7216b276410e84db3be86c1647d6f856 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#![feature(box_syntax, box_patterns)]
use std::cmp::max;
// Recursive structs must be referenced or be Box'd
enum Tree<T: PartialOrd> {
Empty,
Node(T, Box<Tree<T>>, Box<Tree<T>>)
}
impl<T: PartialOrd> Tree<T> {
fn insert(self, x: T) -> Tree<T> {
match self {
Tree::Empty =>
Tree::Node(x, Box::new(Tree::Empty), Box::new(Tree::Empty)),
Tree::Node(value, left, right) => {
if x < value {
Tree::Node(value, Box::new(left.insert(x)), right)
} else {
Tree::Node(value, left, Box::new(right.insert(x)))
}
}
}
}
fn depth(&self) -> i32 {
match *self {
Tree::Empty => 0,
Tree::Node(_, ref left, ref right) =>
1 + max(left.depth(), right.depth())
}
}
}
fn main() {
let tree = Tree::Empty.insert(5).insert(4).insert(3).insert(6).insert(2);
let num = tree.depth();
print!("Depth is: {}", num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment