Skip to content

Commit 854b62e

Browse files
committed
Added random node java - CTCI
1 parent 557ad83 commit 854b62e

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* This code has been checked for syntax errors and typos,
3+
* some of the code in CTCI folder haven't. Hit me up if you want to run them
4+
* and check for typos :) love
5+
*/
6+
import java.util.*;
7+
public class MyClass {
8+
public static void main(String args[]) {
9+
int[] nums = new int[] {
10+
1, 2, 4, 6, 8, 10, 12, 14, 16
11+
};
12+
TreeNode node = new TreeNode(0);
13+
for (int num : nums) {
14+
node.insert(num);
15+
}
16+
// Now we can use the get random node function
17+
for (int i = 0; i < 10; i++) {
18+
TreeNode random = node.getRandomNode();
19+
System.out.println(random.data);
20+
}
21+
22+
}
23+
24+
}
25+
class TreeNode {
26+
int data;
27+
int size;
28+
TreeNode left;
29+
TreeNode right;
30+
31+
public TreeNode(int d) {
32+
this.data = d;
33+
this.size = 1;
34+
}
35+
// Get Random node
36+
public TreeNode getRandomNode() {
37+
int leftSize = this.left == null ? 0 : this.left.size;
38+
// Generate a Random
39+
Random random = new Random();
40+
// Get a random node the size of this subtree
41+
int index = random.nextInt(this.size);
42+
// Now we can check if this random index is to the left
43+
// or right
44+
if (index < leftSize) {
45+
return this.left.getRandomNode();
46+
} else if (index == leftSize) {
47+
return this;
48+
} else {
49+
return this.right.getRandomNode();
50+
}
51+
52+
53+
}
54+
55+
// Insert
56+
public void insert(int val) {
57+
if (val < this.data) {
58+
// Go left
59+
if (this.left == null) {
60+
// set it to this.left
61+
TreeNode node = new TreeNode(val);
62+
this.right = node;
63+
} else {
64+
// recurse on the left side
65+
this.left.insert(val);
66+
}
67+
} else {
68+
// Go right
69+
if (this.right == null) {
70+
// set it to this.right
71+
TreeNode node = new TreeNode(val);
72+
this.right = node;
73+
} else {
74+
this.right.insert(val);
75+
}
76+
}
77+
this.size += 1;
78+
}
79+
// Return size and data
80+
public int size() {
81+
return this.size;
82+
}
83+
public int data() {
84+
return this.data;
85+
}
86+
}

0 commit comments

Comments
 (0)