2015-04-20 63 views
0

我目前正在學習數據結構,現在我在BinarySearchTree。BinarySearchTree - isBalanced()方法獲取NullPointerException - Java

實驗問題:「考慮一種二叉搜索樹的方法,該樹決定樹是否高度平衡。」

當我做實驗時,不知何故,我在Test輸出中得到NullPointerException。我不知道爲什麼,我在哪裏得到一個空。 NetBean說錯誤來自BinarySearchTree.isBalanced()

int leftHeight = left.getHeight(); 
    int rightHeight = right.getHeight(); 

    return (tree.getData() == null) || (isBalanced(left) && isBalanced(right) 
             && Math.abs(leftHeight - rightHeight) <= 1); 

你們能幫我嗎?

非常感謝

這是我isBalanced()方法:

public boolean isBalanced(){ 
    return isBalanced(root); 
} 
private boolean isBalanced(BinaryNode<T> tree){ 
    BinaryNode<T> left = tree.getLeftChild(); 
    BinaryNode<T> right = tree.getRightChild(); 


    int leftHeight = left.getHeight(); 
    int rightHeight = right.getHeight(); 

    return (tree.getData() == null) || (isBalanced(left) && isBalanced(right) 
             && Math.abs(leftHeight - rightHeight) <= 1); 
} 

而且這是在BinaryNode類的getHeight()方法

public int getHeight(){ 
    return getHeight(this); // call private getHeight 
} // end getHeight 

private int getHeight(BinaryNode<T> node){ 
    int height = 0; 

    if (node != null) 
     height = 1 + Math.max(getHeight(node.left), 
      getHeight(node.right)); 

    return height; 
} // end getHeight 
+0

某處,您有一個未初始化的變量,並且您在其上調用方法。檢查一下哪個變量,並確保它在調用方法之前被初始化。 – Stultuske

+1

也許你應該學會通過你的代碼進行調試。這很容易,你會學習一種藝術,你會在整個職業生涯中使用。 – Aakash

回答

1

左右的孩子可能是null在你的程序中,所以在isBalanced(BinaryNode<T> tree)你應該先判斷tree != null否則tree.getLeftChild();可能會拋出一個空指針異常。

相關問題