Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 794
gsingh2011 Avatar asked Nov 09 '12 00:11

gsingh2011


1 Answers

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.

like image 81
Eric W. Avatar answered Sep 28 '22 03:09

Eric W.