Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created September 5, 2014 12:22
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 steveklabnik/0104fcbf0ffe08b34009 to your computer and use it in GitHub Desktop.
Save steveklabnik/0104fcbf0ffe08b34009 to your computer and use it in GitHub Desktop.
use std::fmt::Show;
use std::fmt::Formatter;
use std::fmt::FormatError;
enum Tree<T> {
Node(T, Box<Tree<T>>, Box<Tree<T>>),
Nil,
}
impl<T: Ord + Show> Tree<T> {
fn add(&mut self, val: T) {
match *self {
/*
Node(ref v, box Nil, box Nil) => {
if val >= *v {
*self = Node(v, box Nil, box Node(val, box Nil, box Nil));
} else {
*self = Node(v, box Node(val, box Nil, box Nil), box Nil);
}
},
*/
format Node(ref v, ref mut l, ref mut r) => {
if val >= *v {
r.add(val);
} else {
l.add(val);
}
},
Nil => {
*self = Node(val, box Nil, box Nil);
}
}
}
}
impl<T: Ord + Show> Show for Tree<T> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {
match *self {
Node(ref v, ref l, ref r) => write!(f, "{} -> ( {} {} )", v, l, r),
Nil => write!(f, "Nil")
}
}
}
fn main() {
let mut t: Tree<int> = Node(2, box Nil, box Nil);
t.add(3);
println!("{}", t);
}
@eklavya
Copy link

eklavya commented Sep 5, 2014

thanks a lot steve :) remove format in line 22 though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment