如何在Java中获取AVL树的高度



我试过这个函数

private int height(AVLNode t )
{
    return t == null ? -1 : t.height;
}

我不知道这种方法有什么作用,任何人都可以解释它?

默认方法是使用递归来确定高度。

private int height(AVLNode t) {
    return t == null ? -1 : 1 + Math.max(height(t.left), height(t.right));
}
该方法

返回AVLNode的高度,否则返回-1。线路return t == null ? -1 : t.height是三元运算符

相当于

if (t == null) {
    return -1
} else {
    return t.height
}

它返回 AVLNode 的高度。如果 AVLNode 为空,则返回 -1。如果 AVLNode 不为空,则返回 AVLNode 的高度。

private int height(AVLNode t) {
        if (t == null) {
            return 0;
        }
        return 1 + Math.max((t.getLeft() != null ? t.getLeft().getHeight() : -1),
                (t.getRight() != null ? t.getRight().getHeight() : -1));
}

最新更新