#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
Red,
Black,
}
#[derive(Debug, Clone)]
pub struct RBNode<T: PartialOrd> {
pub value: T,
pub left: Option<Box<RBNode<T>>>,
pub right: Option<Box<RBNode<T>>>,
pub color: Color,
}
impl<T: PartialOrd> RBNode<T> {
pub fn new(value: T) -> Self {
RBNode {
value,
left: None,
right: None,
color: Color::Red,
}
}
pub fn is_red(&self) -> bool {
self.color == Color::Red
}
pub fn is_black(&self) -> bool {
self.color == Color::Black
}
pub fn is_red_node(node: &Option<Box<Self>>) -> bool {
node.as_ref().is_some_and(|n| n.is_red())
}
pub fn rotate_left(mut self: Box<Self>) -> Box<Self> {
let mut new_root = self.right.take().expect("Right child must exist for left rotation");
new_root.color = self.color;
self.color = Color::Red;
self.right = new_root.left.take();
new_root.left = Some(self);
new_root
}
pub fn rotate_right(mut self: Box<Self>) -> Box<Self> {
let mut new_root = self.left.take().expect("Left child must exist for right rotation");
new_root.color = self.color;
self.color = Color::Red;
self.left = new_root.right.take();
new_root.right = Some(self);
new_root
}
pub fn flip_colors(&mut self) {
self.color = match self.color {
Color::Red => Color::Black,
Color::Black => Color::Red,
};
if let Some(left) = &mut self.left {
left.color = match left.color {
Color::Red => Color::Black,
Color::Black => Color::Red,
};
}
if let Some(right) = &mut self.right {
right.color = match right.color {
Color::Red => Color::Black,
Color::Black => Color::Red,
};
}
}
}