AVL树的平衡程序

时间:2018-11-03 15:04:23

标签: algorithm data-structures binary-search-tree avl-tree

根据我对AVL树的理解,对于每个节点,左右子树的高度最多应相差1。

这是代码,我想出了在插入新节点时平衡高度的方法。从新节点向上传播到根节点,将重复执行以下方法

private Node balance(Node x) {
    if (Math.abs(height(x.left) - height(x.right)) <= 1) {
        return x;
    }
    // left sub tree is heavier than right sub tree
    if (height(x.left) > height(x.right)) {
        // right sub tree of left sub tree is heavier than left sub tree of left sub tree
        if (height(x.left.left) < height(x.left.right)) {
            leftRotate(x.left);
        }
        return rightRotate(x);
    }
    // right sub tree is heavier than left sub tree
    else {
        // left sub tree of right sub tree is heavier than right sub tree of right sub tree
        if (height(x.right.left) > height(x.right.right)) {
            rightRotate(x.right);
        }
        return leftRotate(x);
    }
}

当我看着MIT solutions (Page 5)时,如果将节点插入不平衡节点的左子树的左子树中,似乎他们执行的是左旋转,然后右旋转:

enter image description here

根据我的理解,如果我们在不平衡节点的左子树的左子树中插入一个节点,则应该只向右旋转,而不是向左旋转以及随后向右旋转。

我在这里想念什么?我执行正确了吗?

1 个答案:

答案 0 :(得分:1)

您确实在第5页的referenced document中发现了一个错误。

第4页上的图片是正确的,但是第5页上的实现是错误的,可能是拼写错误。

逻辑上,第4-7行的线应在左右方向上反映第8-11行的线。考虑到这一点,显然那里存在错误。

第5行应交换 left right -否则使用Settings->Compiler而不是<来解决问题- -,像这样:

5 如果 height left [ y ])< height right [ y ])

您在这方面的实现是正确的。