计算AVL树的平衡因子

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

大家好!

我不知道如何计算AVL树中节点的平衡因子。有人可以解释吗?

这是我发现的计算余额的代码:

size_t height() const
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return left_h < right_h ? right_h + 1 : left_h + 1;
        }

        signed char balance()
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return right_h - left_h;
        }

此外,这是带有已计数余额的AVL树的示例:

Balances of a Nodes

预先感谢!

c++ algorithm data-structures avl-tree
1个回答
0
投票

作为维基百科states

在二叉树中,节点的平衡因子被定义为其两子树的高度差。

因此,为了计算节点的平衡,您必须计算其子节点的高度。

让我们分析计算余额的代码:

signed char balance()
{
    // calculate height of the children
    // check whether left is absent, if yes: 0, else calculate height on left 
    size_t left_h = (left == nullptr) ? 0 : left->height();
    // the same with right
    size_t right_h = (right == nullptr) ? 0 : right->height();

    // return the difference of heights of the right child and the left child
    return right_h - left_h;
}
© www.soinside.com 2019 - 2024. All rights reserved.