HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Smallest(k) in red-black tree. How is it O(logn)?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
smallestredlognhowtreeblack

Problem

Is it the same as find minimum for a binary search tree?
I know recoloring runs in O(logn) and rotations are O(1).

Even if we are wanting it to find the 'k-th' smallest key in the red-black tree.

Could someone help me understand it in more detail? Thank you!

Solution

The idea is to use an algorithm whose running time is linear in the height, which is $O(\log n)$ in a red-black tree. As JarkkoL mentions, you can maintain a count of the number of children in every subtree without effecting the asymptotic running time of the usual operations (insert, delete and search). You then go down the tree. Suppose you're at a vertex $v$ whose two children have subtrees of sizes $L,R$. If $k = L+1$ then $v$ is the $k$th smallest. If $k L$ then you descend to the right child and replace $k$ by $k-L-1$. This algorithm runs in time $O(\log n)$.

Context

StackExchange Computer Science Q#30460, answer score: 4

Revisions (0)

No revisions yet.