2016-12-01 63 views
0

我是一個初學Java的學生,並有家庭作業,需要我使用遞歸構建一個簡單的BST。應該很簡單,但它給我一些麻煩。插入一個BST,「方法插入(myclass.TreeNode,int)是未定義類型myclass」

構造函數類和main()方法如下

public static class TreeNode 
{ 
    TreeNode LeftLink; 
    int  Content; 
    TreeNode RightLink; 

} 
// end class TreeNode 

public static void main(String[] args) throws IOException 
{ 
    TreeNode T = null; 
    int  H, i; 

    T = BuildSearchTree(); 

    H = Height(T); 
    System.out.println("The number of nodes on the tree is " + NodeCount(T)); 
    System.out.println("The height of the tree is " + H); 
    for (i = 0; i <= H; i++) 
     System.out.println("The number of nodes on level " + i + " is " + CountLevel(T,i)); 
    // end for 
} 

我的任務是填補建立在不修改已提供給我任何一個BinarySearchTree方法提供給我。

BinarySearch Tree方法向用戶請求一個用整數填充的文件,並遞歸地從它構建一個BST。

我的編譯器(Eclipse中)是給我我的插入方法的標題下的錯誤「的方法插入(myclass.TreeNode,INT)是未定義的類型MyClass的」

我相信這事做方式T = BuildSearchTree();在主要方法中聲明,但坦率地說,我不知道發生了什麼。

我有什麼到目前爲止

public static TreeNode BuildSearchTree() throws IOException { 

    Scanner Keyboard = new Scanner(System.in); 

    System.out.println("enter the name of your word file (please include ''.data'' or ''.txt'' when inputting file name) (number of words in the word file must be less than 30.)"); 

    String datafile = Keyboard.next(); 

    Scanner InputFile = new Scanner(new File(datafile)); 

    int[] data = new int[1000]; 

    while(InputFile.hasNext()){ 
     int i; 
     data[i]=InputFile.nextInt(); 
       i++; 
     } //end while 

    for(int i=0; i<1000; i++){ 
    TreeNode T = insert(T, data);} //end for 




    private static TreeNode insert(TreeNode node, int content) 
    { 


     if (node == null) 
     { 
      node.Content=content; 
     } 

     else if (content <= node.Content) 
      { 
       insert(node.LeftLink, content); 
      } 

     else 
      { 
       insert(node.RightLink, content); 
      }          
     } 
    return node; 
}//end insert method 

return T; 

}//end BuildSearchTree 
+0

爲什麼'在'BuildSearchTree'中聲明插入'?根據我的教授的 – 4castle

+0

,我只能編輯BuildSearchTree中的代碼。如果我可以將我的插入方法放在外面,我可以輕鬆地完成這件事。 –

+0

您在BuildSearchTree方法的結尾處​​丟失了一個大括號。我會*不推薦在代碼行的末尾加上花括號,因爲它會弄亂自動縮進。如果您將該大括號放在自己的行上,然後自動縮進,這將更容易看到。 – templatetypedef

回答

0

Java不允許嵌套函數,所以完成代碼BuildSearchTree()啓動代碼插入前()。

將呼叫轉接至T = insert(T, data);插入應該是這樣的T = insert(T, data[i]);

您需要聲明T外循環,如果你想在循環之後使用它。

你不能假定數據文件的元素少於1000個,所以你可能想使用java.util.ArrayList而不是數組。您需要使用從待命環文件實際讀取的項目數插入,而不是1000

while循環的字面意義應該是這樣的:

ArrayList<Integer> data = new ArrayList<Integer>; 
    while(InputFile.hasNext()){ 
     data.add(InputFile.nextInt()); 
    } //end while 
    TreeNode T = new TreeNode(); 
    for(i=0; i<data.length(); i++){ 
     T = insert(T, data[i]); 
    } //end for 
    return T;