【问题标题】:Implementing an AVL Tree实现 AVL 树
【发布时间】:2018-09-29 00:18:47
【问题描述】:

我正在尝试按照here 的指南实施 AVL 树。我在让它工作时遇到了一些问题。目前我在插入的“右右大小写”中收到此错误。具体在这一行:

// Right Right Case
if (balance < -1 && theData > root->right->data)
    leftRotate(root);

我得到的错误是:

Exception thrown: read access violation.
root._Mypair._Myval2->right._Mypair._Myval2 was nullptr.

如果有人能帮我解决这个问题,我将不胜感激。

这是我的代码:

#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <stack>
#include <queue>

struct Node {
    int data;
    int height;
    std::unique_ptr<Node> left = nullptr;
    std::unique_ptr<Node> right = nullptr;

    Node(const int& x, const int& y, std::unique_ptr<Node>&& p = nullptr, std::unique_ptr<Node>&& q = nullptr) :
        data(x),
        height(y),
        left(std::move(p)),
        right(std::move(q)) {}

    Node(const int& data) : data(data), height(1) {}

};
std::unique_ptr<Node> root = nullptr;

int height(std::unique_ptr<Node>& root) {
    if (!root) return 0;
    return root->height;
}

void rightRotate(std::unique_ptr<Node>& y) {
    std::unique_ptr<Node> x = std::move(y->left);
    std::unique_ptr<Node> T2 = std::move(x->right);

    // Perform rotation
    x->right = std::move(y);
    x->right->left = std::move(T2);

    // Update heights
    x->right->height = std::max(height(x->right->left), height(x->right->right)) + 1;
    x->height = std::max(height(x->left), height(x->right)) + 1;
}

void leftRotate(std::unique_ptr<Node>& x) {
    std::unique_ptr<Node> y = std::move(x->right);
    std::unique_ptr<Node> T2 = std::move(y->left);

    // Perform rotation
    y->left = std::move(x);
    y->left->right = std::move(T2);

    // Update heights
    y->left->height = std::max(height(y->left->left), height(y->left->right)) + 1;
    y->height = std::max(height(y->left), height(y->right)) + 1;

}

int heightDiff(std::unique_ptr<Node>& root) {
    if (!root) return 0;

    return height(root->left) - height(root->right);
}

void insert(std::unique_ptr<Node>& root, const int& theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
    // Perform normal BST insertion
    if (root == nullptr) {
        root = std::move(newNode);
        return;
    }

    else if (theData < root->data) {
        insert(root->left, theData);
    }

    else {
        insert(root->right, theData);
    }

    // Update height of this ancestor node
    root->height = 1 + std::max(height(root->left), height(root->right));

    // Get the balance factor of this ancestor node to check whether this node became unbalanced
    int balance = heightDiff(root);

    // If this node become unbalaced, then we have 4 cases

    // Left Left Case
    if (balance > 1 && root->left && theData < root->left->data)
        rightRotate(root);

    // Right Right Case
    if (balance < -1 && root->right && theData > root->right->data)
        leftRotate(root);

    // Left Right Case
    if (balance > 1 && root->left && theData > root->left->data) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Left Case
    if (balance < -1 && root->right && theData < root->right->data) {
        rightRotate(root->right);
        leftRotate(root);
    }
}

auto findMin(std::unique_ptr<Node>& root) {
    while (root->left != nullptr) root = std::move(root->left);
    return root.get();
}

void deleteNode(std::unique_ptr<Node>& root, const int& theData) {
    // Step 1: Perform regular deletion for BST
    if (!root) return;
    else if (theData < root->data) deleteNode(root->left, theData);
    else if (theData > root->data) deleteNode(root->right, theData);

    else {
        // Case 1: No child
        if (root->left == nullptr && root->right == nullptr) {
            root = nullptr;
        }

        // Case 2: One child
        else if (root->left == nullptr) {
            root = std::move(root->left);
        }

        else if (root->right == nullptr) {
            root = std::move(root->right);
        }

        // Case 3: Two children
        else {
            auto temp = findMin(root->right);
            temp->data = root->data;
            deleteNode(root->right, temp->data);
        }
    }


    // Step 2: Update height of the current node
    root->height = 1 + std::max(height(root->left), height(root->right));

    // Step 3: Get the balalce factor of the this node (to 
    // check whether this node became unbalanced)
    int balance = heightDiff(root);

    // If this node becomes unbalanced, then there are 4 cases

    // Left Left Case
    if (balance > 1 && heightDiff(root->left) >= 0)
        rightRotate(root);

    // Left Right Case
    if (balance > 1 && heightDiff(root->left) < 0) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Right Case
    if (balance < -1 && heightDiff(root->right) <= 0)
        leftRotate(root);

    // Right Left Case
    if (balance < -1 && heightDiff(root->right) > 0) {
        rightRotate(root->right);
        leftRotate(root);
    }
}

void inorderTraversal(std::unique_ptr<Node>& root) {
    if (!root) {
        inorderTraversal(root->left);
        std::cout << root->data << " ";
        inorderTraversal(root->right);
    }
}

void preorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        std::cout << root->data << " ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }
}

void postorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        std::cout << root->data << " ";
    }
}

void DFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::stack<Node const *> s;
    s.push(root.get());

    while (!s.empty()) {
        auto p = s.top();
        s.pop();

        if (p->right != nullptr) s.push(p->right.get());
        if (p->left != nullptr) s.push(p->left.get());

        std::cout << p->data << " ";
    }
}

void BFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::queue<Node const *> q;
    q.push(root.get());

    while (!q.empty()) {
        auto p = q.front();
        q.pop();

        if (p->left != nullptr) q.push(p->left.get());
        if (p->right != nullptr) q.push(p->right.get());

        std::cout << p->data << " ";
    }
}

bool exists(int d) {
    auto temp = root.get();
    while (temp != nullptr) {
        if (temp->data == d) {
            return true;
        }
        else {
            if (d > temp->data) {
                temp = temp->right.get();
            }
            else {
                temp = temp->left.get();
            }
        }
    }
    return false;
}

int main() {

    //        8
    //      /    \
    //    4       10
    //   / \     /  \
    //  2   6   9    12

    //insert(root, 8);
    //insert(root, 10);
    //insert(root, 4);
    //insert(root, 2);
    //insert(root, 6);
    //insert(root, 12);
    //insert(root, 9);


  /* Constructing tree given in the above figure */
    insert(root, 9);
    insert(root, 5);
    insert(root, 10);
    insert(root, 0);
    insert(root, 6);
    insert(root, 11);
    insert(root, -1);
    insert(root, 1);
    insert(root, 2);

    /* The constructed AVL Tree would be
            9
           /  \
          1    10
        /  \     \
       0    5     11
      /    /  \
     -1   2    6
    */

    printf("Preorder traversal of the constructed AVL "
        "tree is \n");
    preorderTraversal(root);

    //deleteNode(root, 10);

    /* The AVL Tree after deletion of 10
            1
           /  \
          0    9
        /     /  \
       -1    5     11
           /  \
          2    6
    */

    //printf("\nPreorder traversal after deletion of 10 \n");
    //preorderTraversal(root);

    /*inorderTraversal(root);
    std::cout << "\n";

    preorderTraversal(root);
    std::cout << "\n";

    postorderTraversal(root);
    std::cout << "\n";

    DFS(root);
    std::cout << "\n";

    BFS(root);
    std::cout << "\n";

    exists(4) ? std::cout << "Yes" << std::endl : std::cout << "No" << std::endl;*/


    std::cin.get();
}

【问题讨论】:

  • 通常,在实现树时,您可以通过将std::unique_ptr&lt;Node&gt; left, right; 替换为std::unique_ptr&lt;Node&gt; children[2]; 来减少重复(从而减少复制粘贴错误的机会),由enum {LEFT_CHILD, RIGHT_CHILD}; 支持
  • 最好的建议是逐步使用调试器并找出树的状态以及导致您取消引用 nullptr 的原因。
  • 代码的布局方式为此类错误的发生留下了很多机会。避免错误的最好方法是使它们在逻辑上是不可能的。我看到至少有两个可能的错误原因。 1) Node 构造函数之一未能初始化 height。因此,它的任何使用都是未定义的行为。 2) 缺乏错误检查。示例:leftRotate 无法检查 x 不为空,y 不为空。您的异常指的是空指针访问这一事实高度暗示此类错误是您的错误。哦,使用调试器告诉你代码在哪里崩溃了。
  • 我给你的建议是学习如何使用调试器。了解如何有效地使用调试器是每个 C++ 开发人员必备的技能。您说您已将错误与“插入的正确正确案例”隔离开来。优秀的。现在,在一张纸上写下你希望你的代码在这种情况下做什么。然后,启动调试器并单步执行您的程序,一次一行,将它正在做的事情与您写下的内容进行比较。一旦可观察到的行为与预期的不同,您就发现了您的错误及其原因。问题解决了。
  • x->right = std::move(y); y->left = std::move(T2);在第一个语句中, y 不拥有对象。所以使用y->left是无效的。

标签: c++ c++11 avl-tree


【解决方案1】:

我注意到您已修复 std::move() 问题。但是您可能需要在您的程序中添加以下行。

void rightRotate(std::unique_ptr<Node>& y) {
    ....
    x->height = std::max(height(x->left), height(x->right)) + 1;
    y = std::move(x);
}

void leftRotate(std::unique_ptr<Node>& x) {
    ...
    y->height = std::max(height(y->left), height(y->right)) + 1;
    x = std::move(y);
}

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多