Red-Black Tree Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Red-Black Tree runs in O(log n) time and O(n) space, in Rust as in every other language.
- ✓No red-black tree. The ordered collections BTreeMap and BTreeSet are B-trees, so Rust is a language where the standard ordered map is deliberately not the structure this topic describes.
- ✓Use BTreeMap. If you genuinely need a red-black tree, represent it as an arena of nodes in a Vec with usize indices for left, right and parent, which sidesteps ownership entirely.
- ✓The Rust trap: A red-black tree needs parent pointers, because both the insert and the delete fix-up walk upward from the modified node.
- ✓BTreeMap holds up to eleven key-value pairs per node, so a lookup touches roughly log base eleven of n cache lines against log base two for any binary tree.
What Red-Black Tree actually is
Red-Black Tree in Rust: what you actually reach for
Rust implementation
use std::collections::BTreeMap;
// Rust's standard ordered map is a B-TREE, not a red-black tree, and the
// difference is deliberate: a B-tree splits on the way DOWN, so it never
// walks back up and never needs a parent pointer.
fn main() {
let mut m: BTreeMap<u64, &str> = BTreeMap::new();
m.insert(200, "b");
m.insert(100, "a");
m.insert(300, "c");
// The ordered operations a hash map cannot answer.
let scan: Vec<_> = m.range(150..=300).collect();
assert_eq!(scan.len(), 2);
assert_eq!(m.range(..150).next_back(), Some((&100, &"a"))); // floor
assert_eq!(m.range(150..).next(), Some((&200, &"b"))); // ceiling
}
// If you DO need a red-black tree, the arena is the safe encoding.
// Parent pointers are cycles, so Rc + Weak means a runtime borrow check
// on every access and a fallible upgrade in every rotation. Indices have
// neither problem, and the whole tree is one allocation.
type Idx = u32;
const NONE: Idx = u32::MAX;
#[derive(Clone, Copy, PartialEq)]
enum Color { Red, Black }
struct Node<K, V> {
key: K,
value: V,
color: Color,
left: Idx,
right: Idx,
parent: Idx, // an index, NOT a pointer: no cycle, no Weak, no RefCell
}
pub struct RedBlackTree<K, V> {
nodes: Vec<Node<K, V>>,
root: Idx,
}
impl<K: Ord, V> RedBlackTree<K, V> {
pub fn new() -> Self {
Self { nodes: Vec::new(), root: NONE }
}
fn is_red(&self, i: Idx) -> bool {
i != NONE && self.nodes[i as usize].color == Color::Red
}
pub fn get(&self, key: &K) -> Option<&V> {
let mut i = self.root;
while i != NONE {
let n = &self.nodes[i as usize];
match key.cmp(&n.key) {
std::cmp::Ordering::Equal => return Some(&n.value),
std::cmp::Ordering::Less => i = n.left,
std::cmp::Ordering::Greater => i = n.right,
}
}
None
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Red-Black Tree?
No red-black tree. The ordered collections BTreeMap and BTreeSet are B-trees, so Rust is a language where the standard ordered map is deliberately not the structure this topic describes.
What is the most common Rust mistake when implementing Red-Black Tree?
A red-black tree needs parent pointers, because both the insert and the delete fix-up walk upward from the modified node. A parent pointer is by definition a cycle, so the safe-Rust encoding is Rc together with Weak, which makes every access a runtime borrow check and every rotation a sequence of upgrades that can fail. That is why almost every real Rust implementation uses raw pointers inside unsafe, and it is a large part of why the standard library chose a B-tree instead: a B-tree insert descends and splits on the way down, so it never needs to walk back up and never needs a parent pointer. The lesson generalises. When an algorithm requires upward links, Rust is telling you to pick a different algorithm rather than to fight the borrow checker.
How does Red-Black Tree actually perform in Rust?
BTreeMap holds up to eleven key-value pairs per node, so a lookup touches roughly log base eleven of n cache lines against log base two for any binary tree. On a million entries that is about six memory stalls instead of twenty, which is the practical reason the standard library made this choice. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.