Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::map auto balance itself

I know that mainstream implementations of STL map/set use black-red trees. My question is: do these implementations also auto-balance the tree when inserting/deleting elements?

If not, then when the elements are sorted and inserted, it will always append to the rightmost place. The worst lookup cost is O(n).

So, does the black-red tree auto-balance itself?

like image 934
Troskyvs Avatar asked Aug 04 '26 04:08

Troskyvs


2 Answers

Take a look at the insert and erase std::map operations.

It is guaranteed that the worst complexity for these operations is logarithmic.

In fact it is not important which type of a tree is used to implement an std::map. But this tree must provide necessary complexity for insert, erase and some other operations. Basically it means that the tree must be balanced (and, of course, auto-balance itself when elements are inserted into or removed from).

The same is true for an std::set.

like image 176
Edgar Rokjān Avatar answered Aug 05 '26 19:08

Edgar Rokjān


Yes. Red-black trees perform node rotations to ensure that the tree remains balanced

like image 20
doron Avatar answered Aug 05 '26 19:08

doron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!