이진 검색 트리에 "포함"함수를 쓰려고합니다. "처리되지 않은 예외를 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'- 따라서, 나는 결과가 거짓으로 기대.
"delete temp;" 그 공간을 풀어 주시겠습니까? @ pippin1289 - 문제가 해결되었지만 솔루션이 여전히 컴파일되지 않습니다. – Suede
그냥 삽입 파일의 다른 버전을 복사하고'contains'로 이름을 변경 했습니까? 왜 새로운 노드를 만들 필요가 있습니까? 반환 후 포인터를 삭제하려고하는 이유는 무엇입니까? 컴파일러가 도달 할 수없는 코드를 경고하지 않았습니까? 코드 디버깅을 위해 무엇을 했습니까? – DanielKO