我想爲二叉搜索樹編寫一個「包含」函數。在編譯「BST.exe中的0x77291CB3(ntdll.dll)未處理的異常時收到以下錯誤:0xC00000FD:堆棧溢出(參數:0x00000001,0x001E2FFC)」。以下是我的代碼。二叉搜索樹包含函數
struct Node {
int data;
Node* leftChild;
Node* rightChild;
Node() : leftChild(NULL), rightChild(NULL) {}
};
struct BST {
Node* root;
BST() : root(NULL) {}
void insert(int value);
bool contains(int value);
};
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;
}
}
bool BST::contains(int value) {
Node* temp = new Node();
temp->data = value;
Node* current;
current = root;
if(temp->data == current->data) { // base case for when node with value is found
std::cout << "true" << std::endl;
return true;
}
if(current == NULL) { // base case if BST is empty or if a leaf is reached before value is found
std::cout << "false" << std::endl;
return false;
}
else { // recursive step
current = (temp->data < current->data) ? (current->leftChild) : (current->rightChild);
return contains(temp->data);
}
}
int main() {
BST bst;
bst.insert(5);
bst.contains(4);
system("pause");
}
既然這樣,我會插入帶有值的單個節點「5」,我會搜索二叉搜索樹與值的節點「4」 - 所以,我希望結果是假的。
doesnt「delete temp;」釋放那個空間? @ pippin1289 - 這似乎解決了我遇到的一些問題,但該解決方案仍然不能編譯 – Suede
是隻是我還是你只是複製'insert'函數的另一個版本並將其重命名爲'contains'?爲什麼你需要構建一個新的節點呢?爲什麼你要在返回後刪除一個指針?編譯器沒有警告你這是無法訪問的代碼?你做了什麼來嘗試調試你的代碼? – DanielKO