2014-03-07 2 views
0

그래서 열쇠가 주어진 루트가 매개 변수로 주어진 이진 트리에 대한 지우기 기능에 일하고 있어요. 트리의 구조의 정의있다 : 나는 그것을 실행하려고하면바이너리 트리의 지우기 기능에 오류가 있습니까? (C++)

struct BST_Node { 
string key; 
string things; //not relevant to this function 
BST_Node * left, * right; 
}; 
    typedef BST_Node * BST; 

그러나, 어떤 이유로, 내 첫 번째 경우는 충돌 계속가. 변화 :

if(current && current->left == NULL && current->right==NULL) 

편집 : 당신이 current == NULL 여부를 확인하지 않고 current -> left에 액세스

void BST_delete(string key, BST & tree) { 

//before is just the predecessor 
BST_Node* before = NULL; 
BST_Node* current = tree; 

while(current!= NULL){ 
    if(current->key == key) 
    { 
     break; 
    } 
    else{ 
     before = current; //the node before current 
     if(key < current->key) 
     { 
      current = current->right; 
     } 
     else{ 
      current = current->left; 
     } 
     } 
} 


//FIRST CASE - has no children, so just deleting the Node. 
      //then assigning the "before" node to point to NULL since it was originally  pointing to the node that was just deleted. 
(need to check if the left or right of "before" pointed to "current" 

if(current -> left == NULL && current->right==NULL) 
{ 
    if(before->right == current) 
    { 
     before->right == NULL; 
    } 
    else if(before->left == current) 
    { 
     before->left == NULL; 
    } 

    delete current; 
} 
+0

BST_delete는 정확히 무엇을해야할까요? 그리고 어떤 오류가 있습니까? –

+0

@ChrisMaes 삭제해야 할 노드 (대상 노드)가 주어지고 그 노드를 가리키는 키가 주어집니다. 내가 그것을 실행할 때 단지 충돌. 그것은 비록 컴파일합니다. –

답변

0

아마 당신이 변경하려는 if(key < current->key) 당신이 테스트 크리스를 해결 한 후

if(key > current->key) 
+0

아하 네 말이 맞아. 나는 assert (current! = NULL)을 넣었고 sign을>로 바꿨다. 어떻게 혼합했는지 모르겠다. 그러나, 나는 아직도 제대로 작동하지 않는 것 같습니다. 논리가 맞습니까? –

0

에 Maes가 제안했습니다. 변경해야 할 수도 있습니다.

before->right == NULL; 

과제에 하나만 있어야합니다.

before->right = NULL; 
관련 문제