Search code examples
javatreered-black-tree

Do red-black trees have to be in sorted order?


I have a pretty simple question here: Do red-black trees have to be in sorted order? I ask this because the small box on the right side of the wikipedia page (http://en.wikipedia.org/wiki/Red–black_tree) says that search time is O(log(n)); however, wouldn't this only be true if the tree was sorted. On the other hand though, the properties s


Solution

  • Red black trees are sorted trees (the whole all RB trees are sorted binary trees, but not all sorted binary trees are red black trees thing). The difference between a plain binary tree and a red black tree is that RB trees guarantee that search time will be log2(n) because they're balanced. In essence, it guarantees that the number of layers for n nodes will never be more than log2(n), keeping the binary search in check.

    A plain binary tree with no balancing will not always produce a log2(n) time complexity. For example, if I have a tree like this:

      4
     / \
    3   6
         \
          7
           \
           10
             \
             12
    

    For this unbalanced tree, the actual search time is nearly linear to find 12 (worst-case time complexity, 5 comparisons). For a balanced tree which has at most log2(n) layers, the tree above could be:

         7
       /   \
      4    10
     / \     \
    3   6    12
    

    And so finding any of the lowest-layer nodes will take at most 3 comparisons (which fits log2(n) since it's actually rounded up, ceil[log2(6)] = 3)

    The key here is to remember that the number of layers is functionally equivalent to the number of comparisons you have to make when you start at the root. Red-black trees limit the number of layers to a bare minimum via balancing, while vanilla, unbalanced binary trees don't.