简体   繁体   中英

how to get the height of avl tree in java

i tried this function

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

i don't know what that method do can anyone explain it ?

The default approach is to use recursion to determine the height.

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

It returns the height of the AVLNode. If the AVLNode is null it returns -1. If the AVLNode is not null it returns the height of the AVLNode.

The method returns height of the AVLNode , -1 otherwise. The line return t == null ? -1 : t.height return t == null ? -1 : t.height is a ternary operator

Is equivalent to

if (t == null) {
    return -1
} else {
    return t.height
}
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));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM