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