【问题标题】:Getting read access violation exception, temp was nullptr, when trying to write binary search tree尝试编写二叉搜索树时出现读取访问冲突异常,temp 为 nullptr
【发布时间】:2016-12-11 11:24:59
【问题描述】:

我正在编写二叉搜索树,并在尝试访问我创建的临时节点的值时遇到异常。异常表示抛出异常:读取访问冲突。 temp 为 nullptr。如果有这个异常的处理程序,程序可以安全地继续。错误发生在插入函数中的第一个 if 语句。

#ifndef BINARYSEARCHTREE_H
#define BINARYSEARCHTREE_H
#include <iostream>
#include <stdlib.h>
using namespace std;

template<class T>
class BinarySearchTree {
public:
//Default Constructor
BinarySearchTree() {
    root = NULL;
}

//Constructor with root value
BinarySearchTree(const T& rootItem) {
    root->value = rootItem;
    root->left = NULL;
    root->right = NULL;
}

void insert(const T& item) {
    Node<T> * temp = root;
    bool loop = false;

    while (loop == false) {
        if (temp->value > item) {
            temp = temp->getLeftChild();
        }
        else if (temp->value < item) {
            temp = temp->getRightChild();
        }
        else if (temp->value == item) {
            temp = temp->getRightChild();
        }
        else {
            temp->value = item;
            loop = true;
        }
    }
}

private:
    Node<T> * root = new Node<T>;
};

#endif

【问题讨论】:

  • 你的代码是为Node&lt;T&gt; * root = new Node&lt;T&gt;;编译的吗?
  • 一直运行到插入函数为止。

标签: c++


【解决方案1】:

当您第一次使用默认构造函数创建树时,rootNULL。因此,如果您尝试插入某些内容,temp 也会为空,并且您会遇到访问冲突。

【讨论】:

  • 那么为了让它不为空,我需要用 root 做什么才能给它一个空值?
  • 只需检查它是否为空,如果是则插入只是将 root 设置为具有适当值的新节点。
  • 当我越过根目录插入一些东西时,我仍然得到同样的错误。
  • 是的......因为现在你得到了节点的左子节点,它也是空的。您必须检查每个循环,或者只使用递归。基本上,您想插入一个节点,但实际上您并没有在任何地方创建一个新节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2016-08-01
  • 2016-08-25
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多