views:

106

answers:

2

I came across solution given at http://discuss.joelonsoftware.com/default.asp?interview.11.780597.8 using Morris InOrder traversal using which we can find the median in O(n) time.

But is it possible to acheive the same using O(logn) time? The same has been asked here - http://www.careercup.com/question?id=192816

+2  A: 

If you also maintain the count of the number of left and right descendants of a node, you can do it in O(logN) time, by doing a search for the median position. In fact, you can find the kth largest element in O(logn) time.

Of course, this assumes that the tree is balanced. Maintaining the count does not change the insert/delete complexity.

If the tree is not balanced, then you have Omega(n) worst case complexity.

See: Order Statistic Tree.

btw, BigO and Smallo are very different (your title says Smallo).

Moron
Thanks for the link on Order Statisitc Tree. It heleped answering my question.
Harish
+2  A: 

Unless you guarantee some sort of balanced tree, it's not possible.

Consider a tree that's completely degenerate -- e.g., every left pointer is NULL (nil, whatever), so each node only has a right child (i.e., for all practical purposes the "tree" is really a singly linked list).

In this case, just accessing the median node (at all) takes linear time -- even if you started out knowing that node N was the median, it would still take N steps to get to that node.

Jerry Coffin