2015-03-31 51 views
0

我有一個BST類別的字符串,其全局變量名爲numInsertions,它計算我在BST中插入的次數。我不知道這給正確的結果,因爲我不知道遞歸非常好,請幫我覈實在BST中計算插入次數

public void insert(String key) 
    { 
    if(isEmpty()) 
    { 
     root = new Node(key); 
     numInsertions++; 
    } 
    else 
     numInsertions = 1+insert(key, root); 
    } 
    public int insert(String key, Node curr) 
    { 
    int result = 1; 
    if(key.compareTo(curr.getKey())<0) 
    { 
     if(curr.getLeftChild()==null) 
     { 
     Node newNode = new Node(key); 
     curr.setLeftChild(newNode); 
     } 
     else 
     result = result +insert(key,curr.getLeftChild()); 
    } 
    else 
    { 
     if(curr.getRightChild()==null) 
     { 
     Node newNode = new Node(key); 
     curr.setRightChild(newNode); 
     } 
     else 
     result = result +insert(key,curr.getRightChild()); 
    } 
    return result; 
    } 

回答

0

寫測試用例你類和測試類是正常行爲。假設您的類名爲BST,您可以使用名爲'size()'的方法訪問實例變量'numberOfInserts',可以將用於測試插入(不包含任何第三方庫)的簡單測試用例放置在您的主要方法中測試班。例如:

BST bst = new BST(); 
//test insertion of 100 items 
for (int i = 0; i < 100; i++){ 
    bst.insert(String.valueOf(i)); 
    if (bst.size() != i+1){ 
     throw new Exception("Invalid BST size " + bst.size()); 
    } 
} 

在此示例中,如果類不正常運行,則會引發異常。如果它行爲異常,則可以進入調試器(或使用System.out.println)來嘗試調試該應用程序。