2013-09-22 3 views
0

BST에서 노드 삭제 기능에 문제가 있습니다. 다른 모든 함수는 잘 작동하는지 테스트했지만 노드를 삭제 한 후 트리를 인쇄하면 세그먼트 화 오류가 발생합니다.
여기 삭제 내 코드입니다 :BST에서 노드 삭제

struct Tree 
{ 
    int value; 
    struct Tree *lchild; 
    struct Tree *rchild;  
}*root; 

void print (struct Tree *t) 
{ 
    if (!t) return; 
    if(t->lchild != NULL) 
       print(t->lchild); 

    printf("%d\n",t->value);    

    if(t->rchild != NULL) 
       print(t->rchild); 
} 

내 용의자가 노드를 인쇄에 원인이 문제를 null로 설정하지 방법을 몇 가지 있습니다 :

여기
struct Tree * findinorder (struct Tree *t) 
{ 
    while (t->lchild != NULL) 
     t=t->lchild; 
    return t;  
} 

bool deleteNode (struct Tree *t, int fvalue) 
{ 
bool find = false; //this is to check if node is already found don't go to right sub tree 
struct Tree *inorder; 
if (t==NULL) return find; 
if (t->value == fvalue) 
{ 
    if (t->lchild == NULL && t->rchild == NULL) 
    { 
     free(t); 
    } 
    else { 
     if (t->lchild ==NULL) 
      t= t->rchild; 
     else { 
      if (t->rchild ==NULL) 
       t= t->lchild; 
      else { 
         inorder = findinorder(t->rchild); 
         t->value = inorder->value; 
         free(inorder); 
      } 
     } 
    } 
    return true; 
} 
find = deleteNode(t->lchild, fvalue); 
if (!find) 
    find = deleteNode(t->rchild, fvalue); 
return find; 
} 

인쇄에 대한 트리 구조와 기능입니다 계속.
도와주세요.

그에 따라 rchild/ lchild에 새 참조를 업데이트 할 수 있도록 이전 노드에 대한 포인터를 유지해야

답변

0

:

enter image description here

5에 대한 포인터, 제거 할 node 상상이에 (구체적인 경우)는 다음과 같이 보일 것입니다 :

if (node->rchild && node->rchild->value == 21) { 
    struct Tree *child = node->rchild; 
    node->rchild = child->rchild;    // <-- update reference 
    free(child); 
} 

그러나 노드 21을보고 제거시 어떻게되어야한다고 생각합니까? ... 노드가 발견되면 노드에 대한 포인터에 free을 호출하는 것보다 코드가 복잡해야합니다.

귀하의 경우에는 어떤 상황이 발생합니까? free 해당 노드가 발생하지만 이후에 일단 노드를 통과하면 이전에 free d였던 노드에 대한 포인터가 사용되어 정의되지 않은 동작이 발생합니다.