【问题标题】:Downheap implementation in CC 中的 Downheap 实现
【发布时间】:2020-05-24 08:40:34
【问题描述】:

我有C语言Downheap的源代码,它会在不违反堆属性的情况下向下移动元素(每个节点的值大于/小于或等于其父节点的值,最小/根的最大值元素。)在树的任何节点。

downheap(int k)
{
    int temp, i;
    temp = a[k];
    while(k <= N/2)
    {
        i = 2*k;
        if(i < N && a[i] < a[i+1]) i++;
        if(temp > a[i]) break;
        a[k] = a[i]; k = i;
    }
    a[k] = temp;
}

N 是数组a 的节点总数。我质疑这个程序是否可以从左到右下移节点来保持complete binary tree的属性?如何证明它,因为不存在右节点必须小于/大于左节点的属性。

【问题讨论】:

  • 我觉得你搞错了。 (完整的)二叉树不需要任何形式的顺序。一棵树是二叉的,如果每个节点最多连接到三个边(一个用于父节点和两个子节点),就是这样。您不需要证明结果是二叉搜索树。无论如何,您将很难证明这一点,仅仅是因为堆没有该属性。

标签: c algorithm data-structures


【解决方案1】:
downheap(int k) // k is the index of the item in the heap 
{
  int temp, i;
  temp = a[k]; // Use temp to store the item
  while (k <= N / 2) // Make sure that we don't get outside of the heap boundaries
  {
    i = 2 * k; // Helper line to be used as an index for the children of the node
    if (i < N && a[i] < a[i + 1]) i++; // check which of the children is 
    // Bigger to exchange with the item
    if (temp > a[i]) break; // Item already in-place
    a[k] = a[i];
    k = i; // Exchange item with the children we found to be the biggest
  }
  a[k] = temp; // Put the item in its correct position
}

希望表扬对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-28
    • 2010-12-12
    • 2011-04-04
    • 2012-01-08
    • 2013-01-06
    • 2012-01-05
    • 2013-04-10
    • 2011-09-27
    相关资源
    最近更新 更多