Find median in binary search tree

倖福魔咒の 提交于 2019-12-01 04:34:50

As you mentioned, it is fairly easy to first find the number of nodes, doing any traversal:

findNumNodes(node):
   if node == null:
       return 0
   return findNumNodes(node.left) + findNumNodes(node.right) + 1

Then, with an inorder traversal that aborts when the node number is n/2:

index=0 //id is a global variable / class variable, or any other variable that is constant between all calls
findMedian(node):
   if node == null:
       return null
   cand = findMedian(node.left)
   if cand != null:
        return cand
   if index == n/2:
       return node
   index = index + 1
   return findMedian(node.right)

The idea is that in-order traversal processes nodes in BST in sorted manner. So, since the tree is a BST, the ith node you process, is the ith node in order, this is of course also true for i==n/2, and when you find it is the n/2th node, you return it.


As a side note, you can add functionality to BST to find ith element efficiently (O(h), where h is the tree's height), using order statistics trees.

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