2013-04-12 119 views
0

基本上,我通過從文本文件中讀取一組整數來實現AVL樹,然後使用add()方法填充樹。另外,該程序應該按順序打印整組。AVL樹:解決StackOverflowError

當我運行該程序時,彈出一個StackOverflowError。我認爲這個錯誤是由於add()方法發生錯誤而引發的。

我真的很喜歡是否有人幫助我,因爲我是這種類型的編程新手。

這是主類的一部分:))

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); 

這些是添加(和PrintInOrder(方法:

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); 
     } 
} 

這是Node類:

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); 
} 
+0

請發佈確切的錯誤(與所有細節)。 –

+2

當您有無限遞歸時,堆棧溢出「彈出」。您可以手動在一個小例子上跟蹤您的代碼,或者進入調試器並讓機器爲您做。認爲。讓別人來修正你的錯誤並不是學習的好方法。 – Gene

+1

我真的不知道爲什麼,因爲這不值得我的時間。但是調查無限遞歸也可以通過查看遞歸條件並詢問自己在什麼情況下會繼續被調用來完成。 – Dan

回答

1

由於堆棧溢出通常發生在遞歸中。使用您的IDE並在您已完成清除的位置設置中斷,然後進行調試。穿過它。

+0

我認爲問題是當我從add()方法調用Height_Reset()方法時,因爲當我禁用它時,它工作正常。我不知道它有什麼問題。 – user2275998