java eclipse You are to write a program name BSTree.java that will: 1. Generate
ID: 3858220 • Letter: J
Question
java eclipse
You are to write a program name BSTree.java that will: 1. Generate 100 random integer numbers ranging from 1 - 99. 2. Store these numbers in a data structure of your choice and display the data on the screen. DO NOT SORT THIS DATA STRUCTURE. 3. Now build a Binary Search Tree using this set of numbers. You MUST insert the values into the tree starting from the first element of your Data Structure and go sequentially. 4. After building the tree, use an infix recursive method to display the data on the screen. 5. To build the Binary Search Tree, you must create your own Linked List.Explanation / Answer
import java.util.*;
import java.io.*;
import java.util.Random;
public class BST
{
public class Node// Binary tree implementation
{
int val;// Value assign to node
Node left;// left pointer of node
Node right;// right of node
Node(int val_)
{
val = val_;
}
}
Node root;
void insert(int val) {
root = insertHelper(root, val);
}
Node insertHelper(Node root, int val) {
if (root == null) {
root = new Node(val);// if empty return root as new node
return root;
}
if (val < root.val)// If curr val is less than parent make it left child
root.left = insertHelper(root.left, val);
else if (val > root.val)// If curr val is less than parent make it right child
root.right = insertHelper(root.right, val);
/* Bactrack here return the not changed node*/
return root;
}
void infix(Node node)
{
if (node == null)
{
return;
}
/* call on left child */
infix(node.left);
/* visit node */
System.out.print(node.val + " ");
/* call on right child */
infix(node.right);
}
public static void main(String[] args)
{
Random rand = new Random();// Random in-built class
int[] arr = new int[100];// store random numbers in array
for (int i = 0; i < 100; i++)
{
int n = rand.nextInt(99);// range 1-99
arr[i] = n;
}
BST bst = new BST();// make object of BST
for (int val : arr)// iterate array of random mumbers
{
bst.insert(val);// insert into bst
}
bst.infix(bst.root);// print in infix traversal
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.