Red-Black Tree Implementation in Go
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 Go as in every other language.
- ✓Nothing. Go has no ordered map and no tree in the standard library; the built-in map is a hash with deliberately randomised iteration order.
- ✓Use a sorted slice with slices.BinarySearch for read-mostly data, or take a maintained tree package.
- ✓The Go trap: Go ports of this structure very often use the left-leaning red-black variant, which adds the extra invariant that red links lean left and thereby cuts the number of cases in the fix-up roughly in half, making the code much shorter and much easier to get right.
- ✓Each node is an individual allocation and Go uses a non-moving collector, so the nodes stay scattered wherever they were allocated.
What Red-Black Tree actually is
Red-Black Tree in Go: what you actually reach for
Go implementation
package rbtree
// Left-leaning red-black (Sedgewick): the extra invariant "red links lean
// left" halves the number of fix-up cases.
//
// HAZARD: the LLRB delete algorithm is NOT interchangeable with the
// standard red-black delete. Mixing an LLRB insert with a classic delete
// leaves a valid binary search tree that has quietly stopped being
// balanced, every lookup still returns the right answer, so every test
// passes, and the only symptom is degradation toward O(n) on adversarial
// input. Take BOTH halves from one published variant.
const (
red = true
black = false
)
type Node struct {
Key int
Value string
Left, Right *Node
Color bool
}
func isRed(n *Node) bool {
// Legal on a nil receiver-style check: nil links are black.
return n != nil && n.Color == red
}
func rotateLeft(h *Node) *Node {
x := h.Right
h.Right = x.Left
x.Left = h
x.Color = h.Color
h.Color = red
return x
}
func rotateRight(h *Node) *Node {
x := h.Left
h.Left = x.Right
x.Right = h
x.Color = h.Color
h.Color = red
return x
}
func flipColors(h *Node) {
h.Color = !h.Color
h.Left.Color = !h.Left.Color
h.Right.Color = !h.Right.Color
}
func Insert(h *Node, key int, value string) *Node {
if h == nil {
return &Node{Key: key, Value: value, Color: red}
}
switch {
case key < h.Key:
h.Left = Insert(h.Left, key, value)
case key > h.Key:
h.Right = Insert(h.Right, key, value)
default:
h.Value = value
}
// The three LLRB fix-up cases, in this order.
if isRed(h.Right) && !isRed(h.Left) {
h = rotateLeft(h)
}
if isRed(h.Left) && isRed(h.Left.Left) {
h = rotateRight(h)
}
if isRed(h.Left) && isRed(h.Right) {
flipColors(h)
}
return h
}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 Go-specific trap
Performance in Go, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Red-Black Tree?
Nothing. Go has no ordered map and no tree in the standard library; the built-in map is a hash with deliberately randomised iteration order.
What is the most common Go mistake when implementing Red-Black Tree?
Go ports of this structure very often use the left-leaning red-black variant, which adds the extra invariant that red links lean left and thereby cuts the number of cases in the fix-up roughly in half, making the code much shorter and much easier to get right. The hazard is that the left-leaning variant has its own delete algorithm, and the two are not interchangeable: pasting a standard red-black delete into a left-leaning insert, which is an easy thing to do when assembling code from two sources, produces a tree that stays a valid binary search tree and quietly stops being balanced. Every test passes because lookups still return the right answers, and the only symptom is that performance degrades toward linear on adversarial input. Pick one variant and take both halves from it.
How does Red-Black Tree actually perform in Go?
Each node is an individual allocation and Go uses a non-moving collector, so the nodes stay scattered wherever they were allocated. A sorted slice is one contiguous block and wins clearly whenever writes are rare. 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 full price for a tool, check the student deals on AI and developer tools listed 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.