2016-11-26 34 views
1

我想通過預置樹遍歷來填充數組,但我認爲我已經在如何保留計數器正確。我的toString()方法調用preorder方法,但它只輸出null。我怎樣才能解決這個問題?如何通過遞歸方法來保持BST數組填充時的計數

public AVLTreeNode[] preorder() 
{ 
    /* 
    * return an array of AVLTreeNodes in preorder 
    */ 
    AVLTreeNode[] preorder = new AVLTreeNode[size]; 
    int count = 0; 
    return preorder(root, count, preorder); 
} 

private AVLTreeNode[] preorder(AVLTreeNode data, int count, AVLTreeNode preorder[]) 
{ 
    if (data == null) 
    { 
     return preorder; 
    } 
    preorder[count] = data; 
    if (data.getLeft() != null) 
    { 
     preorder(data.getLeft(), count++, preorder); 
    } 
    if (data.getRight() != null) 
    { 
     preorder(data.getRight(), count++, preorder); 
    } 
    return preorder; 
} 

回答

0

count有錯誤的價值,因爲與count++preorder後續調用的count實際值傳遞給方法和事後count增加。在從左節點count返回後,其值可能會比傳遞給右節點的呼叫的值高。解決辦法有兩個:

  1. 使用全局private int count;,並呼籲preorder之前將其設置爲0

  2. 返回新count代替AVLTreeNode[]並將其分配給該方法的本地count,以獲得正確的值。 AVLTreeNode[] preorder也可以是一個私有變量。

+0

現在我得到一個輸出,但它不是正確的。通過輸入{3,1,5,2},它給出輸出{3,1,5,null}。我檢查了該樹包含值2,它回來了。任何想法爲什麼它會錯過1的正確孩子? – scraig