簡體   English   中英

如何在java中獲取avl樹的高度

[英]how to get the height of avl tree in java

我試過這個功能

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 的高度。 如果 AVLNode 為空,則返回 -1。 如果 AVLNode 不為空,則返回 AVLNode 的高度。

該方法返回AVLNode高度,否則返回 -1。 該行return t == null ? -1 : t.height return t == null ? -1 : t.height是一個三元運算符

相當於

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));

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM