views:

69

answers:

2

Hey everyone.

I have a problem with the rb-trees. according to wikipedia, rb-tree needs to follow the following:

  1. A node is either red or black.
  2. The root is black. (This rule is used in some definitions and not others. Since the root can always be changed from red to black but not necessarily vice-versa this rule has little effect on analysis.)
  3. All leaves are black.
  4. Both children of every red node are black.
  5. Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.

As we know, an rb-tree needs to be balanced and has the height of O(log(n)). But, if we insert an increasing series of numbers (1,2,3,4,5...) and theoretically we will get a tree that will look like a list and will have the height of O(n) with all its nodes black, which doesn't contradict the rb-tree properties mentioned above. So, where am I wrong??

thanks.

+3  A: 

A bit further down in the article:

Insertion begins by adding the node much as binary search tree insertion does and by coloring it red.

anon
@Neil, the newly inserted red node may be repainted into black during the run of algorithm. So its color is not really important.
Pavel Shved
+2  A: 

Your example contradicts property number 5, so it's not a valid Red-Black tree.

The tree we have is:

b(1, nil, b(2, nil, b(3, nil, b(4, nil, b(5, nil, nil)))))

so to get to the last two leaves (the children of node 5), we have to visit five black nodes (represented by each b), to get to the leaf under node 4 we have to visit four black nodes, etc. That means that there are simple paths from the root to some of this descendants containing a different number of black nodes, which invalidates property 5.

fortran
Property #5 says "to any of its descendant leaves" - this tree only has *one* leaf.
anon
@Neil no, the leaves are the "nil" nodes, so it has 6.
fortran
@fortran In my book, and in every data structure book I've ever read, a leaf is a node with no children.
anon
@Pavel there's no need for that, maybe my tone was excessive...
fortran
@Neil, quoting the same wikipedia entry, "The leaf nodes of red-black trees do not contain data". They're just dummy black nodes.
Pavel Shved
@Neil so what can we deduct from it? With your definition I still see six leaves and five nodes with children.
fortran