Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Implement inorder traversal without using recursion) Implement the inorder meth

ID: 3763907 • Letter: #

Question

(Implement inorder traversal without using recursion) Implement the inorder
method in BST using a stack instead of recursion. Write a test program that
prompts the user to enter 10 integers, stores them in a BST, and invokes the
inorder method to display the elements.

I've gotten the part on implementing the inorder method. My main concern now is the test class. This is what I'm currently tinkering with:

import java.util.Scanner;

public class TestBTSStack {

   public static void main(String[] args) {
      
       final int NUM = 10;

       Scanner input = new Scanner(System.in);
       System.out.println("Enter 10 integers: ");
       int i = input.nextInt();
      
       // Create an object for BST of type Integer
       Integer[] numbers = new Integer[i];
       BSTStack<Integer> intTree = new BSTStack<Integer>(numbers);

      
       //Call to inorderUsingStack method of intTree
       System.out.println(" Inorder using Stack: ");
       intTree.inorderUsingStack();

   }
}

I am mainly having trouble in trying to convert the primative int into the Integer class.

Explanation / Answer

import java.util.Scanner;
import java.util.Stack;
/* Class BSTNode */
class BSTNode
{
BSTNode left, right;
int data;

/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
}

/* Class BST */
class BST
{
private BSTNode root;

/* Constructor */
public BST()
{
root = null;
}
public void inorderNR()
{
Stack<BSTNode> s = new Stack<BSTNode>();
BSTNode cur = root;
while(true)
{
while(cur!=null)
{
s.push(cur);
cur=cur.left;
}
if(s.empty())
break;
cur = s.pop();
System.out.print(cur.data+" ");
cur= cur.right;
}
System.out.println();
}
public void buildrandom(int[] a)
{
for(int i=0;i<a.length;i++)
{
insert(a[i]);
}
}
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.data)
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
}

/* Class BinarySearchTree */
public class BinarySearchTree
{
public static void main(String[] args)
{   
Scanner in = new Scanner(System.in);
/* Creating object of BST */
BST bst = new BST();
int[] a = new int[10];
System.out.println("Binary Search Tree Test enter numbers aeperated by space");
for(int i=0;i<10;i++)
{
a[i] = in.nextInt();
}
bst.buildrandom(a);
bst.inorderNR();
}
  
}