How can I find a sequence of elements that, if inserted into a red/black tree, would be balanced purely by changing colors rather than performing rotations?
-
1Welcome to Stack Overflow! I don't fully understand your question. Are you asking for a sequence of elements that, if you inserted them into a red/black tree, would only require color changes to balance? Are you looking for a series of elements that, if inserted into a tree, could be colored to form a red/black tree with no further work required? Or something else? – templatetypedef Jun 23 '20 at 19:00
-
thanks! yes, a sequence of elements that, if I inserted them into a red-black tree, would only require color changes to balance – Kasra Jun 23 '20 at 19:12
1 Answers
You would need to ensure that the new node is always filling out the bottom-most unfilled layer of the RB tree. For example if you had a tree with two nodes it would always be the unbalanced side, like wise if your tree was of four nodes it would be one of the three remaining slots on the third 'row'.
Being able to do this with arbitrary data would pretty much require that arbitrary data to already be sorted (whether in an array or otherwise). Of course, if you're creating an RB tree from already sorted data you shouldn't even need color changes, all the upper-level nodes can be black while any nodes in an unfilled layer (of which there can only be one) will be red if there are missing nodes, or can be all red or all black if there are no missing nodes. If your data is not sorted you will eventually run into a situation where the next available nodes don't fit the available slots.

- 14,104
- 1
- 12
- 23