use std::rc::Rc;
use std::cell::RefCell;
pub struct BinaryTree{
val: i64,
left: Option<Rc<RefCell<BinaryTree>>>,
right: Option<Rc<RefCell<BinaryTree>>>
}
impl BinaryTree{
pub fn new(val: i64)-> Option<Rc<RefCell<BinaryTree>>>{
return
Some(Rc::new(
RefCell::new(
BinaryTree{
val,
left: None,
right: None
}
)
)
)
}
pub fn insert_left(&mut self, left: Option<Rc<RefCell<BinaryTree>>>) {
self.left = left;
}
pub fn insert_right(&mut self, right: Option<Rc<RefCell<BinaryTree>>>) {
self.right = right;
}
pub fn traverse(&self){
print!("{:?}\n",self.val);
match self.left.as_ref(){
Some(left) =>{
left.borrow().traverse();
},
None =>{
}
}
match self.right.as_ref(){
Some(right) =>{
right.borrow().traverse();
}
None =>{
}
}
}
pub fn print2DUtil(&self, mut space: i64){
space = space + 10;
match self.right.as_ref(){
Some(right) => {
right.borrow().print2DUtil(space);
}
None => {
}
}
println!();
for i in 10..space{
print!(" ")
}
println!("{:?}\n", self.val);
match self.left.as_ref(){
Some(left) => {
left.borrow().print2DUtil(space);
}
None => {
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let a = BinaryTree::new(1);
let b = BinaryTree::new(2);
let c = BinaryTree::new(3);
let d = BinaryTree::new(10);
let mut a_ref = a.as_ref().unwrap().borrow_mut();
a_ref.insert_left(b.clone());
a_ref.insert_right(c.clone());
b.as_ref().unwrap().borrow_mut().insert_left(d.clone());
a_ref.traverse();
drop(a_ref);
}
#[test]
fn test_print2DUtil(){
let a = BinaryTree::new(1);
let b = BinaryTree::new(2);
let c = BinaryTree::new(3);
let d = BinaryTree::new(10);
let mut a_ref = a.as_ref().unwrap().borrow_mut();
a_ref.insert_left(b.clone());
a_ref.insert_right(c.clone());
b.as_ref().unwrap().borrow_mut().insert_left(d.clone());
a_ref.print2DUtil(0);
}
}