AVL树是一颗二叉查找树,需要逻辑规则来检查并修正可能出现的不平衡。

package TreePackage;
public class AVLTree<T extends Comparable<? super T>>
             extends BinarySearchTree<T> implements SearchTreeInterface<T>
{
    public AVLTree()
    {
        super();
    }

    public AVLTree(T rootEntry)
    {
        super(rootEntry);
    }
}

单右旋转的算法:

Algorithm rotateRight(nodeN)
// 修正给定结点nodeN的不平衡,因为在nodeN的左孩子的左子树中添加了结点
nodeC = nodeN的左孩子
将nodeC的右孩子赋给nodeN的左孩子
将nodeN赋给nodeC的右孩子
return nodeC

右旋转的实现:

private BinaryNode<T> rotateRight(BinaryNode<T> nodeN)
{
    BinaryNode<T> nodeC = nodeN.getLeftChild();
    nodeN.setLeftChild(nodeC.getRightChild());
    nodeC.setRightChild(nodeN);
    return nodeC;
}

双旋转等价于两次单旋转,执行双旋转的方法是各自调用执行单旋转的方法。

右-左双旋转算法:

Algorithm rotateRightLeft(nodeN)
// 修正给定结点nodeN的不平衡,因为在nodeN的右孩子的左子树中添加了结点

nodeC = nodeN的右孩子
将rotateRight(nodeC)返回的结点赋给nodeN的右孩子
return rotateLeft(nodeN)

算法的实现:

private BinaryNode<T> rotateRightLeft(BinaryNode<T> nodeN)
{
    BinaryNode<T> nodeC = nodeN.getRightChild();
    nodeN.setRightChild(rotateRight(nodeC));
    return rotateLeft(nodeN);
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐