Median of BST in O(logn) time complexity

徘徊边缘 提交于 2019-12-03 16:24:09

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).

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.

Anubhav

We can find the median by using the rabbit and the turtle pointer. The rabbit moves twice as fast as the turtle in the in-order traversal of the BST. This way when the rabbit reaches the end of traversal, the turtle in at the median of the BST.

Please see the full explanation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!