2013-10-23 4 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)를 제거 할 때; 내 주요 기능에서 더 이상 처리되지 않은 예외가 발생하지 않습니다.

다음은 NULL로 leftChildrightChild을 설정하지 않는 당신의 삽입 기능에서 내 구조체

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

포스트 당신의'내 생성자 BST에서 바닥 – Kunal

+0

은 (I 편집 그 아래에) leftChild와 rightChild를 NULL로 설정했으나 루트는 설정하지 않았습니다. BST 생성자 또는 Node Constructor에서 그렇게 할 수 있습니까? – Suede

답변

1

의 초기화이다.

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

에서의 편집 Node' 클래스 – Suede

+0

@Suede 편집을 확인하고'BST'에 생성자를 추가하십시오 – Kunal

+0

원래 게시물에서 편집 했으므로 컴파일되므로 '처리되지 않은 예외'에 대한 유일한 이유가 무엇입니까? – Suede

관련 문제