Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with duplicates in red-black trees?

So I've been(so far unsuccessfully) trying to make my red-black tree implementation work consistently with duplicates, but it seems to always be missing that small something, so here I am.

I tried make the tree lean to one side, but It didn't seem to balance it properly(from the color perspective).I'd like to ask how should one go about adding duplicates to a red-black tree?(apart obviously making the node fat, holding or pointing to duplicate key values).

Not really looking for a code review, more interested in suggestions. So basically the methods(taken from Introduction to Algorithms, Third Edition) I use for insert and balancing are these(while rotations are pretty obvious):

enter image description here

enter image description here

like image 932
jonas rudzionis Avatar asked Mar 18 '16 12:03

jonas rudzionis


1 Answers

If you look at the pseudo-code you wrote here, it is completely agnostic to the question of whether keys are duplicate or not. The code here only looks at the result of comparing keys, and doesn't care if they are identical or not. In fact, unique-key implementations need to go out of their way to make RB-Insert detect duplicate keys. The data structure doesn't care about this naturally, and the algorithms and proofs hold whether there are duplicate keys or not. If you implemented these functions correctly, it should work as is.

I also disagree with the comments advising you to hold what you call "fat nodes". Holding multiple keys is the common implementation of C++'s std::multimap, for example. Not that from a computational complexity point of view, say that you have altogether n keys, but each k are a multiple. Using the "efficient" fat node version, the complexity of the basic find operation will be Θ(log(n / k)) = Θ(log(n) - log(k)); using the multiple key version, the complexity will be Θ(log(n)). In real life cases, probably k << n, which means that the relative difference is negligible.

like image 137
Ami Tavory Avatar answered Oct 23 '22 02:10

Ami Tavory