Hi,
I have made a program to insert values in a Binary Search Tree (BST) in java. I have stored the values in an array and there are eleven values in the array 0..10 random values. However when I am using the condition:
Code:
if(arrIndex<=10)
root = insert(root, data);
else
JOptionPane.showMessageDialog(null, "No more elements left in array");
I am getting overflow message but when I am using:
Code:
if(arrIndex<=10)[/B]
root = insert(root, data);
else
JOptionPane.showMessageDialog(null, "No more elements left in array");
it works. I cant figure out why :
does not work.
My complete program is given below:
Code:
//modified 2016 binary Search Tree Program
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
class TreeNode{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data1){
data = data1;
left = null;
right =null;
}
}
class bst2018 extends JFrame implements ActionListener{
TreeNode root;
String str= null;
int[ ] arr= {7, 1, 9, 0, 3, 8, 10, 2, 5, 4, 6};
int arrIndex;
bst2018( ) {
root = null;
arrIndex=0;
JButton btn1 = new JButton("Insert");
JButton btn2 = new JButton("Inorder");
JButton btn3 = new JButton("Preorder");
JButton btn4 = new JButton("Postorder");
JPanel p = new JPanel();
p.add(btn1);
p.add(btn2);
p.add(btn3);
p.add(btn4);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
add(p);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String str1= "";
String strBtnCaption=e.getActionCommand();
if(strBtnCaption.equals("Insert")) {
insert(arr[arrIndex]);
}
else if(strBtnCaption.equals("Inorder")) {
inorder(root);
JOptionPane.showMessageDialog(null,str );
}
else if(strBtnCaption.equals("Preorder")) {
str = null;
preorder(root);
JOptionPane.showMessageDialog(null,str );
}
else if(strBtnCaption.equals("Postorder")) {
str = null;
postorder(root);
JOptionPane.showMessageDialog(null,str );
}
}
public void insert(int data){
if(arrIndex<10)
root = insert(root, data);
else
JOptionPane.showMessageDialog(null, "No more elements left in array");
}
public TreeNode insert(TreeNode node, int data){
if (node == null){
node = new TreeNode(data);
JOptionPane.showMessageDialog(null, data);
arrIndex++;
}
else {
if(data < node.data)
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
public void inorder(TreeNode r){
if(r !=null)
{
inorder(r.left);
str = str + " " +r.data;
//
inorder(r.right);
}
}
public void preorder(TreeNode r) {
if(r !=null)
{
str = str + " " + r.data;
preorder(r.left);
preorder(r.right);
}
}
public void postorder(TreeNode r) {
if(r !=null)
{
postorder(r.left);
postorder(r.right);
str = str + " " + r.data;
}
}
public static void main(String[ ] args) {
new bst2018();
}
}
Some body please guide me.
Zulfi.