更新 AVL 树的高度和 BF 时遇到问题

问题描述 投票:0回答:1

所以我正在尝试更新 AVL 树的高度和平衡因子 (BF)。我通过使用 updateHeightAndBF() 方法来完成此操作。但是,我的程序不断收到错误消息:

此 updateHeightAndBF 测试没有结论,原因是:java.lang.NullPointerException

这是该方法的代码:

public void updateHeightAndBF(AVLNode<T> currentNode) {
        
        //Store the left child height in a variable (keep in mind the height of a null node; you'll have to account for this!)
        AVLNode<T> leftChild = currentNode.getLeft();
        if (leftChild == null) {
           leftChild.setHeight(-1);
        }
        
        //Store the right child height in a variable (keep in mind the height of a null node; you'll have to account for this!)
        AVLNode<T> rightChild = currentNode.getRight();
        if (rightChild == null) {
           rightChild.setHeight(-1);
        }
        
        //Set the height of the node to be: max(left child's height, right child's height) + 1
        currentNode.setHeight(Math.max(leftChild.getHeight(), rightChild.getHeight()) + 1);
        
        //Set the balance factor of the node to be: left child's height - right child's height
        currentNode.setBalanceFactor(leftChild.getHeight() - rightChild.getHeight());
}

我认为问题是我试图为空节点分配高度?但如果没有子节点(又名空节点),我应该给它一个 -1 的高度。那么,如果程序不允许,我该如何将 -1 的高度分配给空节点呢?

我不知道还能尝试什么。

java nullpointerexception avl-tree
1个回答
0
投票

如果程序不允许,我该如何将 -1 的高度分配给空节点?

尝试将某物分配给无物是没有意义的。

null
表示节点的不存在。相反,您可以将 -1 分配给局部变量,并在计算当前节点的高度时使用它。

这是对你的函数的更正

public int updateHeightAndBF(AVLNode<T> currentNode) {
    AVLNode<T> leftChild = currentNode.getLeft();
    AVLNode<T> rightChild = currentNode.getRight();
    // Calculate the heights of the child nodes
    int leftHeight = leftChild == null ? -1 : leftChild.getHeight();
    int rightHeight = rightChild == null ? -1 : rightChild.getHeight();
    // Use that information to derive the current node's height and balance factor
    currentNode.setHeight(Math.max(leftHeight, rightHeight) + 1);
    currentNode.setBalanceFactor(leftHeight - rightHeight);
}
© www.soinside.com 2019 - 2024. All rights reserved.