【发布时间】: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<T> * root = new Node<T>;编译的吗? -
一直运行到插入函数为止。
标签: c++