简体   繁体   中英

What's the worst-case time complexity of TreeSet?

It is stated here that

TreeSet has a log(n) time complexity guarantuee for add()/remove()/contains().

But TreeSet uses a binary search tree and in the worst case, binary search trees can have O(n) height. How is the log(n) complexity "guaranteed"?

The implementation rebalances the tree upon inserts.

The O(lg n) time bound for insert is guaranteed by the official documentation . This should not come as a surprise: A classic way to implement sets is as some sort of self-balancing binary search tree .

Java libraries are publicly available, so let's go see for ourselves. TreeSet can be found, eg, here . It is implemented in terms of TreeMap , which is in turn here . As @Don Roby points out, the underlying data structure is a Red-Black tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM