Once the tree is created, an add() function lets the user add a device. The tree then proceeds to insert the new key just as if it were a binary search tree—only to check and fix any errors immediately afterward. Where a binary search tree could use a simple if condition to decide the direction it proceeds in, in the red-black tree, the direction has a larger impact, and nesting if conditions will result in chaotic, unreadable code.
Thus, let's create enum first, so any time the direction (example, insert, position of a node relative to another node, and so on) has to be decided, we can rely on that enum. The same goes for the tree's color:
#[derive(Clone, Debug, PartialEq)]
enum Color {
Red,
Black,
}
#[derive(PartialEq)]
enum RBOperation {
LeftNode,
RightNode,
}
Now, the add() function can use Rust's match clause to nicely structure the two branches:
pub fn add(&mut self, device: IoTDevice) {
self.length += 1;
let root = mem::replace...