forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomNodeInBT.java
82 lines (70 loc) · 2.82 KB
/
RandomNodeInBT.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.rampatra.trees;
import java.util.Random;
/**
* You are implementing a binary tree class from scratch, which 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
* for getRandomNode().
*
* @author rampatra
* @since 2019-04-03
*/
public class RandomNodeInBT {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
int size; // num of nodes in left subtree + 1 + num of nodes in right subtree
TreeNode(int val, int size) {
this.val = val;
this.size = size;
}
TreeNode getRandomNode() {
int randomNum = new Random().nextInt(this.size); // generates a random num from 0 to size - 1 (both inclusive)
/*
the below makes all nodes equally likely because the probability is distributed
evenly (approximately) depending on the number of children
*/
if (this.left != null && randomNum < this.left.size) {
return left.getRandomNode();
} else if (this.right != null && randomNum > this.right.size) {
return right.getRandomNode();
} else {
return this;
}
}
}
public static void main(String[] args) {
/*
The BST looks like:
4
/ \
2 8
/ \ / \
1 3 6 9
*/
TreeNode treeRoot = new TreeNode(4, 7);
treeRoot.left = new TreeNode(2, 3);
treeRoot.right = new TreeNode(8, 3);
treeRoot.left.left = new TreeNode(1, 1);
treeRoot.left.right = new TreeNode(3, 1);
treeRoot.right.left = new TreeNode(6, 1);
treeRoot.right.right = new TreeNode(9, 1);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println(treeRoot.getRandomNode().val);
System.out.println("-------");
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
System.out.println(new Random().nextInt(8));
}
}