The exercise I'm trying to solve is
You are implementing a binary search tree class from scratch, which, in addition, to insert, find and delete, has a method
getRandomNode()
which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm forgetRandomNode()
, and explain how you would implement the rest of the methods.
The answer from the book is:
1 class TreeNode {
2 private int data;
3 public TreeNode left;
4 public TreeNode right;
5 private int size = 0;
...
12 public TreeNode getRandomNode() {
13 int leftSize = left == null ? 0 : left.size();
14 Random random = new Random();
15 int index = random.nextInt(size);
16 if (index < leftSize) {
17 return left.getRandomNode();
18 } else if (index == leftSize) {
19 return this;
20 } else {
21 return right.getRandomNode();
22 }
23 }
...
55 }
But here is the problem. With this algorithm, I don't see how nodes are equally likely to be chosen. In line 16, it says if leftsize > index,
where index
is a number from 0 to size
, then the algorithm will continue with the left node, otherwise the right node. It only works when the tree has a depth of 2. When the tree is taller, the probability of each node being chosen will not be equal.
Am I wrong? Does this algorithm work?
getRandomNode()
on the trees and see if the distribution of the count returned of each node is uniform. It's not a definitive answer, but should give you some perspective. $\endgroup$ – ryan Nov 6 '17 at 22:33