Bst* removeTree(Bst* bst, char data[]) { //노드 삭제 함수 Bst* temp; if(bst==NULL) return bst; else if(strcmp(bst->value,data)>0) //데이터를 비교하여 왼쪽 오른쪽으로 트리를 이동시킨다. bst->leftchild=removeTree(bst->leftchild, data); else if(strcmp(data,bst->value)>0) bst->rightchild=removeTree(bst->rightchild, data); else if(strcmp(data,bst->value)==0) { //삭제할 노드를 찾은 경우 if(bst->leftchild!=NULL && bst->rightchild!=NULL) { //삭제할 노드의 자식이 두개인 경우 leftdepth=accountDepth(bst->leftchild); //양 서브트리의 깊이와 노드수를 계산 leftnumnode=accountNumnode(bst->leftchild); rightdepth=accountDepth(bst->rightchild); rightnumnode=accountNumnode(bst->rightchild); if(leftdepth>rightdepth) { //노드의 깊이가 깊은 쪽에서 작거나 큰값의 노드를 골라서 제거 temp=selectmax(bst->leftchild); bst->value=temp->value; bst->leftchild=removeTree(bst->leftchild, temp->value); } if(leftdepth<rightdepth) { temp=selectmin(bst->rightchild); bst->value=temp->value; bst->rightchild=removeTree(bst->rightchild, temp->value); } if(leftdepth==rightdepth && leftnumnode>rightnumnode) { //깊이가 같아서 노드수를 비교하여 노드를 고른다. temp=selectmax(bst->leftchild); bst->value=temp->value; bst->leftchild=removeTree(bst->leftchild, temp->value); } if(leftdepth==rightdepth && leftnumnode<rightnumnode) { temp=selectmin(bst->rightchild); bst->value=temp->value; bst->rightchild=removeTree(bst->rightchild, temp->value); } if(leftdepth==rightdepth && leftnumnode==rightnumnode) { //깊이와 노드수 모두 같아 왼쪽서브트리에서 선택한다. temp=selectmax(bst->leftchild); bst->value=temp->value; bst->leftchild=removeTree(bst->leftchild, temp->value); } } else { //자식 노드가 하나거나 없을 경우의 제거 수행 temp=bst; if(bst->leftchild==NULL) bst=bst->rightchild; else if(bst->rightchild==NULL) bst=bst->leftchild; free(temp); } } return bst; }
Bst* selectmin(Bst* bst) { if(bst==NULL) return NULL; if(bst->leftchild!=NULL) return selectmin(bst->leftchild); else return bst; }
void creathftree(huffmantree T) //£½¨¹þ·òÂüÊ÷ { int i,p1,p2; inithf(T); inputhf(T); for(i=n;i<m;i++) { selectmin(T,i-1,&p1,&p2); T[p1].parent=T[p2].parent=i; T[i].lchild=p1; T[i].rchild=p2; T[i].weight=T[p1].weight+T[p2].weight; } }