Bonus Assignment Solution

1.   Write a program to randomly pick an element of a binary search tree randomly. All the elements should have about equal probability of being selected. Consider the following binary search tree as an example.





4                          7



2                          5



1                          3




If you simulate ipping a coin and choose left or right based on the outcome, node 7 will be selected 50% of the time. We want the probability of node 7 to be selected to be 1/7. Note that the elements in the tree need not be consecutively numbered. There may be gaps between the numbers. Don't assume anything about individual numbers. Just read the numbers from the user as shown below and use your proposed scheme to estimate the probabilities.




Enter the set of numbers for the tree


60 41 72 23 57 1 32


Probabilities after 1000 random selections are


= 0.135000
= 0.135000
= 0.152000
= 0.147000
= 0.156000
= 0.147000
= 0.128000


Insert the numbers into the trees in the order they are listed. Once you build the tree, pick a random element 1000 times and estimate and print the probabilities

Powered by