user2275998
user2275998

Reputation: 1

AVL Tree: solving a StackOverflowError

Basically, I am implementing an AVL tree by reading a set of integers from a text file and then populate the tree by using the add() method. Also, the program is supposed to print in order the set of integers.

As I run the program, a StackOverflowError pops up. I think that this error is being triggered due to something malfunctioning in the add() method.

I would really appreaciate if someone helps me as I am new to this type of programming.

This is part of the Main Class:

 public static void main(String[] args) throws FileNotFoundException
   {

            AVL s1 = new AVL();

            Scanner file = new Scanner(new File("C:\\Users\\Dell\\Desktop\\integers.txt"));

            while(file.hasNext())
            {
               // String str = file.next();

                //int b = Integer.parseInt(str);
                int b = file.nextInt();
                s1.add(b);

            }

            v1.PrintInOrder(v1.root); 

These are the add() and PrintInOrder() methods:

public boolean add(int key)
 {
        root = add(root, key);
        return true;
 }

private Node add(Node b1, int key)
 {

     if(b1 == null)
     {
        return new Node(key);
     }

     if(key < b1.element){
            b1.left = add(b1.left, key);
     }
     else
     {
            b1.right = add(b1.right, key);
     }

     int Left_Height = getHeight(b1.left);
     int Right_Height = getHeight(b1.right);

     // a height imbalance requires that two subtrees differ by two
     if(Math.abs(LeftHeight - RightHeight )== 2)
         return Balance(n1);
     else
     {
        n1.ResetHeight();
        return b1;
     }
 }

   public void PrintInOrder(Node b1){
      if(b1 != null){
        PrintInOrder(b1.left);
        System.out.println(b1.element);
        PrintInOrder(b1.right);
      }
 }

This is the Node class:

public class Node {

Node left;
Node right;
int element;
int height;

public Node(int keys){
    this(keys, null, null);
}

public Node(int d, Node right1, Node left1){
    element = d;
    height = 0;
    left = left1;
    right = right1;
}


// This method recalculates the height if the right or left subtrees have been altered
 public void ResetHeight(){

    int LeftHeight = AVL.getHeight(left);
    int RightHeight = AVL.getHeight(right);
    height = 1 + Math.max(LeftHeight,RightHeight);
}

Upvotes: 0

Views: 562

Answers (1)

Joban
Joban

Reputation: 1337

Since stack overflows commonly occur in recursion. Use your IDE and set a break at locations where you have done recusion, then debug. Step through it.

Upvotes: 1

Related Questions