Getting a random number from a binary tree in O(log n) time

≯℡__Kan透↙ 提交于 2019-12-08 19:42:48

问题


Is it possible to get a uniformly distributed random value (calling the function means it's equally likely to get any value in the tree) from a balanced binary search tree in O(log n) time?

My initial idea was to generate a random number 0, 1, or 2. If 0, take the left path from the current node, if 1, take the right path, otherwise the value of the node is the random value. If you hit a leaf node, take the value of that node. I don't think this would be randomly distributed though.

This is out of curiosity, not for a specific application.

Let me know if you need any clarifications.

An example is if you have the tree

     1
    / \
   2   5
       /
      3

The numbers 1, 2, 3, and 5 would be returned uniformly when calling int get_random_number()

Clarification: All other normal BST operations should remain O(log n), like insert(), delete(), etc.


回答1:


Your idea will not create a random distribution. The root has a 1/3 chance of being picked no matter the size of the tree.

If you know the number of elements in the tree, generate a number k between 1 and N, and get the kth largest element of the tree. See here for a way to do that in O(logn) for balanced trees.



来源:https://stackoverflow.com/questions/13300537/getting-a-random-number-from-a-binary-tree-in-olog-n-time

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