Question: import java.util.Random; import java.util.Scanner; import java.util.Stack; class BinarySearchTree { public static class Node { int data; Node left; Node right; public Node ( int data

import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
class BinarySearchTree {
public static class Node {
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinarySearchTree(){
root = null;
}
public void insert(int data){
Node newNode = new Node(data);
if (root == null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while (true){
parent = current;
if (data < current.data){
current = current.left;
if (current == null){
parent.left = newNode;
return;
}
} else if (data > current.data){
current = current.right;
if (current == null){
parent.right = newNode;
return;
}
} else {
// Duplicate values are not allowed (you can modify this part as needed)
return;
}
}
}
public void iterativeInOrderTraversal(Node root){
if (root == null){
System.out.println("Tree is empty");
return;
}
Stack stack = new Stack<>();
Node current = root;
while (current != null ||!stack.isEmpty()){
while (current != null){
stack.push(current);
current = current.left;
}
current = stack.pop();
System.out.print(current.data +"");
current = current.right;
}
}
public static void main(String[] args){
BinarySearchTree bst = new BinarySearchTree();
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the size of the BST
System.out.print("Enter the size of the BST: ");
int bstSize = scanner.nextInt();
// Prompt the user to enter the minimum and maximum values for random numbers
System.out.print("Enter the minimum value for random numbers: ");
int minValue = scanner.nextInt();
System.out.print("Enter the maximum value for random numbers: ");
int maxValue = scanner.nextInt();
// Generate random numbers and insert them into the BST
Random random = new Random();
for (int i =0; i < bstSize; i++){
int randomNum = random.nextInt((maxValue - minValue)+1)+ minValue;
bst.insert(randomNum);
}
// Display the BST in-order traversal using iterative approach
System.out.println("Binary search tree in-order traversal:");
bst.iterativeInOrderTraversal(bst.root);
// Close the scanner
scanner.close();
}
} This code doesn't work for bigger sizes such as 10000,100000,1000000. Could you please fix that?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!