2012-07-24 2 views
0

huffman 코딩 프로그램 용 이진 트리를 작성하는 코드에 결함이있는 것 같습니다. 이유는 모르겠지만 디버거의 루트 노드를 검사 할 때 왼쪽 노드는 문자 N을 가리키고 오른쪽 노드는 부모 노드를 가리 킵니다. 상위 노드의 왼쪽 노드는 문자 N을 가리키고, 오른쪽 노드는 상위 노드를 가리 킵니다. 그 부모 노드의 왼쪽 자식은 문자 N이고, (이것이 어디로가는 지 알 수 있습니다.) 이전 디버깅에서이진 트리가 잘못 형성되는 경우

huff_sort(nodes); // sort nodes by weight 

    //-------BUILDING TREE------ 
    while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one 
     int w= (**beg).weight + (**(beg+1)).weight; 
     Node* p = new Node; 
     p->set_node(w, '*', *nodes->begin(), *(nodes->begin()+1)); //making it the parent node of the two lowest nodes 
     nodes->erase(nodes->begin(), nodes->begin()+2); 
     unsigned int i = 0; 
     while(w > (*nodes)[i]->weight && i <= nodes->size()){ //finds where to insert the parent node based on weight 
      i++; 
     } 
     if(i > nodes->size()) //if it needs to be inserted at the end 
      nodes->push_back(p); 
     else 
      nodes->insert(nodes->begin()+i, p); 
     delete p; 
    } 

, 나는 huff_sort 기능이 작동하는지 알고 :이 문제는 코드입니다.

+0

대신 std :: map을 사용하지 않는 이유는 무엇입니까? –

+0

@ManofOneWay 어때? (죄송합니다, 프로그래밍에 익숙하지 않습니다.) –

+0

std :: map은 정렬 된 이진 트리로 구현됩니다. http://en.cppreference.com/w/cpp/container/map –

답변

1

루프 끝에서 delete p을 수행하면 포인터가 무효화되고 방금 삽입 한 노드가 해제됩니다.