You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
+17-15Lines changed: 17 additions & 15 deletions
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,6 @@
1
+
packagecom.thealgorithms.datastructures.trees;
2
+
3
+
1
4
/* Author : Suraj Kumar
2
5
Github : https://github.com/skmodi649
3
6
*/
@@ -11,7 +14,7 @@
11
14
Step 2: First create a binary tree using the steps mentioned in the first approach
12
15
Step 3: Now use a method inOrder() that takes a node as input parameter to traverse through the
13
16
binary tree in inorder fashion as also store the values in a ArrayList simultaneously.
14
-
Step 4: Now define a method getrandom() that takes a node as input parameter, in this first call
17
+
Step 4: Now define a method getRandom() that takes a node as input parameter, in this first call
15
18
the inOrder() method to store the values in the arraylist, then find the size of the binary tree and now just generate a random number between 0 to n-1.
16
19
Step 5: After generating the number display the value of the ArrayList at the generated index
17
20
Step 6: STOP
@@ -21,17 +24,17 @@ the inOrder() method to store the values in the arraylist, then find the size of
21
24
importjava.util.ArrayList;
22
25
23
26
// Using auxiliary array to find the random node in a given binary tree
24
-
classNode {
25
-
intitem;
26
-
Nodeleft, right;
27
-
28
-
publicNode(intkey) {
29
-
item = key;
30
-
left = right = null;
31
-
}
32
-
}
33
27
34
28
publicclassTreeRandomNode {
29
+
privateclassNode {
30
+
intitem;
31
+
Nodeleft, right;
32
+
33
+
publicNode(intkey) {
34
+
item = key;
35
+
left = right = null;
36
+
}
37
+
}
35
38
36
39
// Using an arraylist to store the inorder traversal of the given binary tree
37
40
staticArrayList<Integer> list = newArrayList<>();
@@ -44,8 +47,9 @@ public class TreeRandomNode {
44
47
45
48
// Now lets find the inorder traversal of the given binary tree
0 commit comments