Created
September 1, 2016 12:38
-
-
Save anonymous/7216b276410e84db3be86c1647d6f856 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains 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
#![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