AVL树旋转删除节点

时间:2015-11-19 02:53:31

标签: c++ avl-tree

致力于AVL实施。当我尝试执行旋转时,它会删除正在旋转的节点的子节点。到目前为止,我只是开始做对了。我没有在节点中实现父指针,因为我使用BST作为基础。

有没有猜测为什么这会被搞砸?如果需要任何其他信息,我可以发布。我不想为了代码墙的原因上传我的整个课程。

插入

template <typename T>
void AVL<T>::insert(T data)
{
    insert(mRootNode, data);
}

template <typename T>
void AVL<T>::insert(Node<T>*& node, const T &data)
{
    // If the tree is empty, make a new node and make it 
    // the root of the tree.
    if (node == NULL)
    {
        node = new Node<T>(data);
        return;
    }

    // If num is already in tree: return.
    if (node->mData == data)
        return;

    // The tree is not empty: insert the new node into the
    // left or right subtree.
    if (data < node->mData)
    {
        insert(node->mLeft, data);
    }
    else
    {
        insert(node->mRight, data);
    }

    // Check for balance errors
    int balance = getBalance(node);
    bool
        rotL = (balance > 1) && (getBalance(node->mRight) == 1),
        rotR = (balance < -1) && (getBalance(node->mLeft) == -1),
        rotRL = (balance > 1) && (getBalance(node->mRight) == -1),
        rotLR = (balance < -1) && (getBalance(node->mLeft) == 1);

    if (rotR)
    {
        rotateRight(node);
    }
}

右旋转

template <class T>
void AVL<T>::rotateRight(Node<T>*& node)
{
    showTree(); // Show tree before rotation

    Node<T>* other = node->mLeft;
    Node<T>* tmp = other->mRight;

    other->mRight = node;
    node->mLeft = tmp;

    showTree(); // Show tree after rotation
}

余额

template <class T>
int AVL<T>::getBalance(Node<T>* node)
{
    return (node->mRight ? treeHeight(node->mRight) : 0) - (node->mLeft ? treeHeight(node->mLeft) : 0);
}

存根

void StubAVL()
{
    AVL<int> tree;

    cout << "Inserting:  5\n";
    tree.insert(5);

    cout << "Inserting:  8\n";
    tree.insert(8);

    cout << "Inserting:  3\n";
    tree.insert(3);

    cout << "Inserting:  12\n";
    tree.insert(12);

    cout << "Inserting:  9\n";
    tree.insert(9);

    cout << "Inserting:  2\n";
    tree.insert(2);

    cout << "Inserting:  13\n";
    tree.insert(13);

    cout << "Inserting:  0\n";
    tree.insert(0);

    cout << "Inserting:  -1\n";
    tree.insert(-1);

    cout << "Inorder:  ";
    tree.showInOrder();
    cout << endl;

    cout << "Preorder:  ";
    tree.showPreOrder();
    cout << endl;

    cout << "Postorder:  ";
    tree.showPostOrder();
    cout << endl;

    cout << "Node Count = " << tree.nodesCount() << endl;
    cout << "Leaves Count = " << tree.leavesCount() << endl;
    cout << "Height = " << tree.getHeight() << endl;

    cout << "The tree looks like:\n";
    tree.showTree();

    cout
        << "\n\n"
        << "Heights\n";
    tree.showHeight();

    cout
        << "\n\n"
        << "Balances\n";
    tree.showBalance();

    cout << "\n\n";
    system("pause");
}

输出

enter image description here

在插入0之后,↑删除了3个孩子。

0 个答案:

没有答案