题目:给定n个整数,求对应的哈夫曼树的高度

考虑建立哈弗曼树的过程:每次从所有节点中选择最小的两个节点组成新的节点,新节点的权值是两个节点权值之和,并删除这两个
节点。因此我们可以用一个数组来实现。
1 将数组降序排序 (最小的两个在末尾)
2 将数组最后两个元素合并为一个,其层数为原来两个元素的最大层数加1
3 数组长度减一
4 新数组再排序 -->第一步
循环直到数组长度为1

 

struct Node {
int value;
int layer;
};

//降序排列
int cmp(const void *a, const void *b)
{
struct Node *t1 = (struct Node*)a, *t2 = (struct Node*)b;
return (t1->value <= t2->value);
}

int TreeHeight(int *a, int n)
{
struct Node *p = new struct Node[n];
for (int i=0; i<n; i++)
{
p[i].value = a[i];
p[i].layer = 0;
}
while (n>1)
{
qsort(p, n, sizeof(struct Node), cmp);
p[n-2].value += p[n-1].value;
p[n-2].layer = (p[n-2].layer>=p[n-1].layer?p[n-2].layer:p[n-1].layer)+1;
n--;
}

return p[0].layer;
}


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-22
  • 2021-10-13
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2021-11-27
  • 2021-04-17
  • 2021-11-23
  • 2021-05-20
  • 2022-12-23
  • 2021-07-03
相关资源
相似解决方案