[英]Inserting into a binary search tree
我編寫了一個將節點插入二叉搜索樹的函數。 但是,當嘗試在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) {}
};
在插入函數中,您未將leftChild
和rightChild
設置為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
構造函數中將root設置為NULL。 嘗試這些修改。
好像您在BST中沒有發布的構造函數:
struct BST {
Node* root;
void insert(int value);
BST(): root(NULL) { } // add a constructor to initialize root to NULL
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.