2015-10-22 31 views
0

這種方法給了我一個空指針異常,我不知道爲什麼,這是遞歸代碼有問題。我無法弄清楚。在recusive二叉樹方法上的Java空指針異常

public void clearAllSelections(){ 
    //Recursively clear all the selections in the sub-tree of this node 
    //basis: 
    isSelected = false; 
    if(isLeaf()) return; 

    //recursion: 
    childrenRight.clearAllSelections(); 
    childrenLeft.clearAllSelections(); 

} 
+0

childrenRight or childrenLeft is null。使用您的調試器來識別原因。 –

回答

3

isLeaf()檢查是不夠的面前,因爲在二叉樹中的節點可以有一個孩子,所以你必須添加null檢查:

public void clearAllSelections(){ 
    //Recursively clear all the selections in the sub-tree of this node 
    //basis: 
    isSelected = false; 
    if(isLeaf()) return; 

    //recursion: 
    if (childrenRight != null) 
     childrenRight.clearAllSelections(); 
    if (childrenLeft != null) 
     childrenLeft.clearAllSelections(); 

} 
2

做childrenRight和childrenLeft空校驗使函數調用