为了账号安全,请及时绑定邮箱和手机立即绑定

关于哈夫曼树的问题

关于哈夫曼树的问题

邓垚 2016-11-08 18:28:17
#include<iostream>using namespace std;struct element{ int weight; int lchild, rchild, parent;};void Select(element hfmt[], int &i1, int &i2, int &num){ element hfmtw[7]; int min; bool isi1 = false; for (int i = 0; i<num; i++) {  hfmtw[i] = hfmt[i]; } int temp; for (int a = 0; a<num - 1; a++){  if (hfmtw[a].parent != -1){   continue;  }  min = a;  for (int j = a; j<num; j++){   if (hfmtw[j + 1].weight<hfmtw[min].weight)   {    if (hfmtw[j + 1].parent != -1){     continue;    }    min = j + 1;       }  }  if (isi1 == false){   i1 = min;   isi1 = true;  }  else{   i2 = min;   return;  }  temp = hfmtw[a].weight;  hfmtw[a].weight = hfmtw[min].weight;  hfmtw[min].weight = temp; } num++;}void Hfmt(element hfmt[], int w[], int n){ for (int i = 0; i<2 * n - 1; i++){  hfmt[i].parent = -1;  hfmt[i].lchild = -1;  hfmt[i].rchild = -1; } for (int b = 0; b<n; b++){  hfmt[b].weight = w[b]; } int i1 = 0, i2 = 0; int num = n; for (int k = n; k<2 * n - 1; k++) {  Select(hfmt, i1, i2, num);  hfmt[i1].parent = k;  hfmt[i2].parent = k;  hfmt[k].weight = hfmt[i1].weight + hfmt[i2].weight;  hfmt[k].lchild = i1;  hfmt[k].rchild = i2; }}void main(){ element hfmt[7]; int n = 4; int w[] = { 2, 3, 4, 5 }; Hfmt(hfmt, w, n); for (int i=0; i<7; i++) {  cout << hfmt[i].weight << " " << hfmt[i].parent << " " << hfmt[i].lchild << " " << hfmt[i].rchild << endl; }}怎么跟预计的不一样
查看完整描述

1 回答

已采纳
?
慕运维1139315

TA贡献84条经验 获得超21个赞

我调试了一下num++放在return上面,还有for循环把减1去掉,我觉得select用栈好做一点

查看完整回答
反对 回复 2016-11-08
  • 1 回答
  • 0 关注
  • 1364 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信