-2

In a red-black tree with n nodes, what is the maximum number of red nodes (assuming the root is black)?

Is it O(n)?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
marc_
  • 105
  • 1
  • 7
  • O(n) is (or at least appears to be) rather a lazy guess. Show us the argument you followed to determine that. A bit of visualization (draw the tree, colour the nodes) should help you with that. You may get stuck at some point, but that's what we're here for, not to do your thinking for you. – Bernhard Barker Feb 17 '14 at 01:57

1 Answers1

0

If the tree has n nodes and the root is black, there are n - 1 nodes left and n - 1 = O(n), so you're right.

If you want to count/bound number of red nodes in the tree more accurately, you have to know the topology of that tree.

For instance, if the tree is a complete binary tree, according to the definition of the red-black-tree, it can have no red nodes at all.

pkacprzak
  • 5,537
  • 1
  • 17
  • 37
  • @Dukeling yes, in my first sentence I wrote that maximum is O(n) – pkacprzak Feb 17 '14 at 01:55
  • In a red-black tree, a red node can't have a red child, so there can't be `n-1` red nodes (unless `n <= 3`). – Bernhard Barker Feb 17 '14 at 02:03
  • @Dukeling Yeah, of course, but `O(n)` doesn't mean `n - 1`. I mean, every number less or equal `n - 1` is `O(n)`. – pkacprzak Feb 17 '14 at 02:10
  • True, but your answer makes it sound a lot like there can be n-1 red nodes. And there may be a closer bound (it's like saying merge-sort takes O(n^2) time), or perhaps whomever asked OP the question is looking for an exact value, not big-O. And the maximum is the maximum of all topologies, so you don't have to know that. And your last paragraph is largely meaningless with respect to the question, as the question is asking for the maximum. – Bernhard Barker Feb 17 '14 at 03:05