Skip to content

Instantly share code, notes, and snippets.

@stmtk1
Created October 17, 2019 07:45
Show Gist options
  • Save stmtk1/6190165b891b92d8deb533492d9c6d06 to your computer and use it in GitHub Desktop.
Save stmtk1/6190165b891b92d8deb533492d9c6d06 to your computer and use it in GitHub Desktop.
use std::sync::{ Arc, Mutex };
#[derive(Debug)]
struct BinTree {
left: Option<Arc<Mutex<BinTree>>>,
right: Option<Arc<Mutex<BinTree>>>,
value: u64,
}
impl BinTree {
pub fn new(value: u64) -> BinTree {
BinTree {
value,
left: None,
right: None,
}
}
pub fn insert(&mut self, value: u64) {
if value < self.value {
match &self.left {
None => {
self.left = Some(Arc::new(Mutex::new(BinTree::new(value))));
},
Some(left) => {
left.lock().unwrap().insert(value);
},
}
} else {
match &self.right {
None => {
self.right = Some(Arc::new(Mutex::new(BinTree::new(value))));
},
Some(right) => {
right.lock().unwrap().insert(value);
},
}
}
}
pub fn is_contain(&self, value: u64) -> bool {
if value == self.value {
return true;
}
if value < self.value {
match &self.left {
None => false,
Some(left) => left.lock().unwrap().is_contain(value),
}
} else {
match &self.right {
None => false,
Some(right) => right.lock().unwrap().is_contain(value),
}
}
}
}
fn main() {
let mut a = BinTree::new(45);
a.insert(2);
a.insert(10);
a.insert(100);
println!("{}, {}, {}", a.is_contain(2), a.is_contain(10), a.is_contain(100));
println!("{}, {}, {}", a.is_contain(4), a.is_contain(1), a.is_contain(125));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment