러스트 입문 1일차..
use std::cmp::Ordering;
use core::fmt::Display;
enum BST<T: Ord + Display> {
Leaf {
val: T,
left: Box<BST<T>>,
right: Box<BST<T>>,
},
Empty
}
impl<T: Ord + Display> BST<T> {
fn new() -> Self {
BST::Empty
}
fn create(val: T) -> Self {
BST::Leaf {
val,
left: Box::new(BST::Empty),
right: Box::new(BST::Empty)
}
}
fn insert(&mut self, value: T) {
match self {
BST::Leaf {
ref val,
ref mut left,
ref mut right
} => match value.cmp(val) {
Ordering::Greater => right.insert(value),
Ordering::Less => left.insert(value),
_ => { println!("wtf") }
}
BST::Empty => {
*self = BST::create(value);
}
}
}
fn traverse(&self) {
self._traverse(self)
}
fn _traverse(&self, node: &BST<T>) {
match node {
BST::Leaf {
ref val,
ref left,
ref right
} => {
self._traverse(&left);
println!("{:}", val);
self._traverse(&right)
},
_ => {}
}
}
}
fn main() {
let mut bst = BST::new();
bst.insert(30);
bst.insert(20);
bst.insert(10);
bst.traverse();
}