Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of TreeSet iteration?

In my code, Java TreeSet iteration is the dominant time factor. In looking at the system I believe that it is O(n) complexity. Can anyone verify this?

I am thinking that by providing links backward from child node to parent node I could improve the performance.

like image 623
John Smith Avatar asked May 03 '10 15:05

John Smith


People also ask

Can you iterate through a TreeSet?

Iterator can be created over the TreeSet objects. Hence this iterator can be used to traverse or loop through the TreeSet.

Why HashSet is faster than TreeSet?

Simply put, HashSet is faster than the TreeSet.HashSet provides constant-time performance for most operations like add(), remove() and contains(), versus the log(n) time offered by the TreeSet. Usually, we can see that the execution time for adding elements into TreeSet is much more than for the HashSet.

What sorting algorithm does TreeSet use?

According to the API, TreeSet uses a TreeMap internally, which is based on a "Red-Black tree" algorithm.

What is the benefit of using a TreeSet?

TreeSet keeps the elements in order at all times. With ArrayList you just sort when you need to. With TreeSets the key must be embedded in the object you store in the collection.


1 Answers

TreeSet iteration is of course O(n), as can be expect from any sensible tree-walking algorithm.

I am thinking that by providing links backward from child node to parent node I could improve the performance.

TreeMap (which TreeSet is based on) already has such parent references. This is the method it all boils down to:

private Entry<K,V> successor(Entry<K,V> t) {
    if (t == null)
        return null;
    else if (t.right != null) {
        Entry<K,V> p = t.right;
        while (p.left != null)
            p = p.left;
        return p;
    } else {
        Entry<K,V> p = t.parent;
        Entry<K,V> ch = t;
        while (p != null && ch == p.right) {
            ch = p;
            p = p.parent;
        }
        return p;
    }
}
like image 55
Michael Borgwardt Avatar answered Sep 20 '22 03:09

Michael Borgwardt