简体   繁体   中英

Why is TreeSet Iteration O(n) instead of O(n*logn)?

I read a previous question about the time complexity for TreeSet and the answer was that it takes O(n) time. However, I don't understand why it is O(n) to iterate instead of O(n*nlogn).

Each next call takes O(logn) time

So if I iterate through a TreeSet like this:

while (iterator.hasNext()){ //Runs N times
   System.out.println(iterator.next() + " "); //each next is O(logn)
}

I would expect for it to be O(n*logn) and not O(n) because the while loop has N iterations and each iterator.next() call takes O(logn) time.

The worst-case time for one next operation is O(log n) because that's the height of the tree. On average, however, the next element can be found in time O(1) . This is because the whole traversal in essence uses each of the n-1 tree edges twice.

You can implement the iteration for a tree like this:

void print(Node n) {
   if (n.left != null) print(n.left);
   System.out.println(n.value);
   if (n.right != null) print(n.right);
}

The function print is going to be called exactly once for every node so the total iteration time is O(N). You can implement the exact same algorithm iteratively (without recursion). And if you are careful enough you can have a class to keep the iteration state and advance when .next() is called. It's true that the number of function calls between println s is uneven but when you look at it overall you will find that there are exactly N of them.

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