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

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!

• If tree nodes store the size of the subtree it's O(logn), if not it's O(n), AFAIK – JarkkoL Oct 1 '14 at 2:30
• Hint: a Red-Black-tree is a binary search tree. Furthermore, it has logarithmic height (in the worst case). – Raphael Oct 1 '14 at 20:12

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 left child. 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)$.