Red-Black Tree
A red-black tree implementation as a Rust collection type. A red-black tree, is a binary search tree that is approximately balanced.
As such, all binary search tree operations, such as insert, remove, contains, min, max, predecessor, successor have a worst case time complexity of O(log n).
The red-black tree is implemented according to the Cormen et. al. and mostly serves self-educational purpose. Whilst it is a fully functional implementation of a red-black tree, you should probably use either std::collections::BTreeSet or std::collections::BTreeMap, unless you specifically rely on duplicate values being allowed to exist in the tree.
Examples
Binary Search Tree Operations
use RedBlackTree;
let mut rbt: = .map.collect;
rbt.insert;
assert!;
assert_eq!;
assert_eq!;
assert!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Iteration
Iterate nodes of the tree in-order (sorted), as &T, &Node<T> or T.
use ;
let rbt = from_iter;
let first_val: = rbt.iter.next;
assert_eq!;
let first_node: = rbt.iter_node.next;
assert_eq!;
let first_owned_val: = rbt.into_iter.next;
assert_eq!;
Subtrees
Work with subtrees using the node API.
use ;
let mut rbt: = .map.collect;
let subtree: & = rbt.get_node.unwrap;
assert!;
assert!;
// This also allows for (on average), faster predecessor/successor operations,
// since traversal starts from the node directly.
let predecessor: & = subtree.predecessor.unwrap;
assert_eq!;
assert_eq!;
Tree sort in a single line 😀.
Due to the Red-black tree being approximately balanced, this runs in O(n log n).
Though it is still not very efficient, since it requires n separate allocations (one per node) and it is also not in-place.
use RedBlackTree;