You are to write a program name BSTree.java that will: Generate 100 random integ
ID: 3766793 • Letter: Y
Question
You are to write a program name BSTree.java that will:
Generate 100 random integer numbers ranging from 1 – 99.
Store these numbers in a data structure of your choice and display the data on the screen. DO NOT SORT THIS DATA STRUCTURE.
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.
After building the tree, use an infix recursive method to display the data on the screen.
To build the Binary Search Tree, you must create your own Linked List.
Explanation / Answer
import java.util.*;
class BSTNode
{
public BSTNode left,right;
public int data;
public BSTNode()
{
left=null;
right = null;
data = 0;
}
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
}
class BSTree
{
private BSTNode root;
public BSTree()
{
root = null;
}
public BSTree(int n)
{
root = new BSTNode(n);
}
public BSTree(BSTNode node)
{
root = node;
}
public void insert(int n)
{
root = aux_insert(root,n);
}
private BSTNode aux_insert(BSTNode node, int data)
{
if(node == null)
return new BSTNode(data);
if(node.data <= data)
node.right = aux_insert(node.right, data);
else
node.left = aux_insert(node.left, data);
return node;
}
public void inorder()
{
aux_inorder(root);
System.out.println();
}
private void aux_inorder(BSTNode node)
{
if(node==null)
return;
aux_inorder(node.left);
System.out.print(node.data+" ");
aux_inorder(node.right);
}
}
public class TEST{
public static void main(String[] args)
{
Random rnd= new Random();
int[] a = new int[100];
for(int i=0;i<100;i++)
a[i] = rnd.nextInt(99);
System.out.println("the random elements generated are ");
for(int i=0;i<100;i++)
System.out.print(a[i]+" ");
System.out.println();
BSTree b = new BSTree(a[0]);
for(int i=1;i<100;i++)
b.insert(a[i]);
System.out.println("The inorder traversal of tree is :");
b.inorder();
}
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.