Hi, everyone. I'm learning Rust through the course and a now the task is to implement an AVL Tree. I'm using the structs below and already implemented insert, remove and rotate methods. Also I have to implement method get(&self, key: &K) -> Option<&V>
on AVLTreeMap, but now I'm stuck, because borrow()
method of RefCell creates temp values reference to which I cannot return.
pub enum Factor {
LeftHeavy = 1,
RightHeavy = -1,
Balanced = 0,
}
pub struct Node<K, V> {
parent: Option<Weak<RefCell<Node<K, V>>>>,
left: Option<Rc<RefCell<Node<K, V>>>>,
right: Option<Rc<RefCell<Node<K, V>>>>,
balance_factor: RefCell<Factor>,
pub key: K,
pub value: Option<V>,
}
pub struct AVLTreeMap<K, V> {
root: Option<Rc<RefCell<Node<K, V>>>>,
size: usize,
}
impl<K: Ord, V> AVLTreeMap<K, V> {
fn new() -> Self {
AVLTreeMap {
root: None,
size: 0,
}
}
fn get(&self, key: &K) -> Option<&V> {
self.search(&self.root, key)
}
fn search<'a>(&self, node: &'a Option<Rc<RefCell<Node<K, V>>>>, key: &K) -> Option<&'a V> {
return if let Some(ref node) = node {
let borrowed_node = node.borrow();
if borrowed_node.key == *key {
borrowed_node.value.as_ref()
} else if borrowed_node.key < *key {
self.search(&borrowed_node.right, key)
} else {
self.search(&borrowed_node.left, key)
}
} else {
None
}
}
}
Is it even possible to implement such get
method or I should use different children field types?