2013-10-23 253 views
1

我写了一个函数来将节点插入二叉搜索树。但是,当试图在Visual Studio 2013中构建解决方案时,我收到以下错误消息:“BST.exe中0x00FD4CD0的未处理异常:0xC0000005:访问冲突读取位置0xCCCCCCCC”。以下是我的代码。插入二进制搜索树

void BST::insert(int value) { 
    Node* temp = new Node(); 
    temp->data = value; 
    if(root == NULL) { 
     root = temp; 
     return; 
    } 
    Node* current; 
    current = root; 
    Node* parent; 
    parent = root; 
    current = (temp->data < current->data) ? (current->leftChild) : (current->rightChild); 
    while(current != NULL) { 
     parent = current; 
     current = (temp->data < current->data) ? (current->leftChild) : (current->rightChild); 
    } 
    if(temp->data < parent->data) { 
     parent->leftChild = temp; 
    } 
    if(temp->data > parent->data) { 
     parent->rightChild = temp; 
    } 
} 

然后在我的主要功能我:

int main() { 
    BST bst; 
    bst.insert(10); 
    system("pause"); 
} 

当我删除bst.insert(10);在我的主要功能中,我不再收到未处理的异常。

以下是我的结构

struct Node { 
    int data; 
    Node* leftChild; 
    Node* rightChild; 
    Node() : leftChild(NULL), rightChild(NULL) {} 
}; 
struct BST { 
    Node* root; 
    void insert(int value); 
    BST() : root(NULL) {} 
}; 
+0

发表你的'在底部 – Kunal

+0

(我编辑在底部)我将leftChild和rightChild设置为NULL,但不是root。我会在BST构造函数或Node构造函数中做到这一点吗? – Suede

回答

1

的初始化在你插入功能,你不设置leftChildrightChild为NULL。

void BST::insert(int value) { 
    Node* temp = new Node(); 
    temp->data = value; 
    temp->leftChild = NULL; 
    temp->rightChild = NULL; 
    if(root == NULL) { 
     root = temp; 
     return; 
    } 

而且,我不能肯定(因为你还没有发布的构造BST),但在BST构造你可能没有设置根为NULL。尝试这些修改。

好像你没有从您发布什么BST构造:

struct BST { 
    Node* root; 
    void insert(int value); 
    BST(): root(NULL) { } // add a constructor to initialize root to NULL 
}; 
+0

编辑在我的构造BST Node'类 – Suede

+0

@Suede检查编辑并在'BST'中添加构造函数 – Kunal

+0

我在原始文章中对其进行了编辑并编译,所以这是'未处理的异常'的唯一原因? – Suede