【问题标题】:How can one find the last (right most) node on the last level of tree which is a heap (almost complete tree)?如何在树的最后一层即堆(几乎完整的树)上找到最后一个(最右边的)节点?
【发布时间】:2019-01-01 12:50:22
【问题描述】:

我试图在堆的最后一层(树表示)中找到最右边的节点,以便删除最小/最大堆中的特定元素。

几乎所有在线人员都编写了将要删除的节点替换为位于最低级别的堆的最右边节点 - 我完全理解,但我怎样才能找到最后一个节点?

根据我的解决方案:我有一个解决方案,即使用级别顺序遍历(广度优先搜索)遍历该树(堆结构),同时存储节点的地址 - 当有队列中只剩下一个没有子节点的元素,我将用它来替换。本例中最右边的节点是 33

是否有任何其他方法/链接可以使用,因为使用队列似乎很长?

【问题讨论】:

  • 那么这张图片中“最后一层最右边的节点”是什么?
  • 如果您使用二进制堆的数组表示(例如,{ 10, 14, 19, 26, 31, 42, 27, 44, 35, 33 }),最深层中最右边的元素(示例中为 33)是数组中的最后一个元素。所以,如果数组A[]N二叉堆元素,最深层最右边的元素是A[N-1]
  • @EugeneSh。 33 是最后一个
  • @NominalAnimal 我正在创建堆,就像 BST 一样(但其逻辑始终倾向于逐级完成)& 在用于 BFS 的队列中,我正在存储节点的地址。跨度>
  • 使用指向节点的指针数组来表示堆(因此节点本身没有指针)应该更简单/更健壮地实现。这里使用树形结构有更深层次的原因吗?

标签: c data-structures queue heap


【解决方案1】:

让我们看一棵完整的二叉树,忽略存储在节点上的值,但将节点编号为as if they were stored in an array,从根处的 1 开始编号: 如果我们从根遍历到任何目标节点(根本身除外),左边缘(红色)为 0,右边缘(蓝色)为 1,我们会看到一个模式:

Path     Edges   Target (binary)
─────    ──────  ───────────────
1 → 2    0       1 0
1 → 3    1       1 1
1 → 4    0 0     1 0 0
1 → 5    0 1     1 0 1
1 → 6    1 0     1 1 0
1 → 7    1 1     1 1 1
1 → 8    0 0 0   1 0 0 0
1 → 9    0 0 1   1 0 0 1
1 → 10   0 1 0   1 0 1 0
1 → 11   0 1 1   1 0 1 1
1 → 12   1 0 0   1 1 0 0
1 → 13   1 0 1   1 1 0 1
1 → 14   1 1 0   1 1 1 0
1 → 15   1 1 1   1 1 1 1

从根到所需节点的路径与该节点的编号的二进制表示相同(根为1),忽略最高有效二进制数字!

所以,在一棵完整的树中,要到达第K'th 节点,根为1,我们首先找到小于K 的2 的最大幂,并根据其下面的二进制数进行遍历,在降序排列,0 表示左,1 表示右。

假设我们的节点结构类似于

typedef  struct node  node;
struct node {
    struct node  *left;
    struct node  *right;
    /* plus node data fields */
};

然后找到ith 节点,i = 1 for root,可以实现为

node *ith_node(node *root, const size_t i)
{
    size_t  b = i; 

    /* Sanity check: If no tree, always return NULL. */
    if (!root || i < 1)
        return NULL;

    /* If i is 1, we return the root. */
    if (i == 1)
        return root;

    /* Set b to the value of the most significant binary digit
       set in b. This is a known trick. */
    while (b & (b - 1))
        b &= b - 1;        

    /* We ignore that highest binary digit. */
    b >>= 1;

    /* Walk down the tree as directed by b. */
    while (b) {
        if (i & b) {
            if (root->right)
                root = root->right;
            else
                return NULL; /* Not a complete tree, or outside the tree. */
        } else {
            if (root->left)
                root = root->left;
            else
                return NULL; /* Not a complete tree, or outside the tree. */
        }

        /* Next step. */
        b >>= 1;
    }

    /* This is where we arrived at. */
    return root;
}

在实践中,如果你有一个包含N 节点的完整二叉树,ith_node(root, N) 将返回一个指向最终节点的指针。

如果你想要路径,最低有效位是根的第一个边,你可以使用例如

/* (*path) will contain the path to ith node, root being i=1,
   and the return value is the number of steps needed.
   Returns -1 if an error occurs. */
int  path_to_ith(const size_t i, size_t *path)
{
    size_t  b = i;
    size_t  p = 0;
    int     n = 0;

    if (i < 1)
        return -1; /* Invalid i! */

    /* Set b to the value of the most significant binary digit set. */
    while (b & (b - 1))
        b &= b - 1;        

    /* Ignore most significant digit. */
    b >>= 1;

    /* Reverse the rest of the bits in b, into p. */
    while (b) {
        p = (p << 1) + (b & 1);
        b >>= 1;
        n++;
    }

    /* Store path. */
    if (path)
        *path = p;

    /* Return the number of edges (bits) in path. */
    return n;
}

请注意,上面的函数是基于树完成的:即,除了可能的最后一层之外的所有层都被填满,最后一层的所有最左边的节点都被填满。也就是说,如果使用上图所示编号的节点 N 被填充,那么节点 1 到 N-1 也必须被填充。

以上示例中的逻辑有效。但是,由于示例代码是在没有经过适当审查的情况下一次性编写的,因此其中可能存在错误。因此,如果您对示例代码或此答案中的任何地方有任何问题,请在评论中告诉我,以便我可以根据需要进行检查和修复。


请注意,二进制堆通常使用数组表示。

(为了使用正确的数组索引,我们在此处切换到从零开始的索引;即从现在开始,根位于索引 0。)

然后节点没有指针。为了支持删除,我们通常将索引存储到节点所在的堆数组中,否则节点只有数据。 (如果您需要更改键值或删除根以外的条目,您通常会添加一个指定当前堆数组索引的数据字段。不过,它确实有点慢,所以通常不需要它。我会省略它为简单起见。)

typedef  double  heap_key;

typedef struct {
    /* Data only! */
} heap_data;

typedef struct {
    heap_key   key;
    heap_data *val;
} reference;

typedef struct {
    size_t     max;  /* Current max heap size, nodes */
    size_t     len;  /* Number of nodes in this heap */
    reference *ref;  /* Array of references to nodes */
} heap;
#define  HEAP_INIT { 0, 0, NULL }

static inline void heap_init(heap *h)
{
    if (h) {
        h->max = 0;
        h->len = 0;
        h->ref = NULL;
    }
}

请注意,heap 中的引用数组是根据需要动态分配/重新分配的,因此堆的大小没有固有限制(当然,内存除外)。

HEAP_INIT 宏允许在声明时初始化堆。换句话说,heap h = HEAP_INIT; 等价于heap h; heap_init(&amp;h);

将新元素添加到这样的堆中非常简单:

static int heap_add(heap *h, heap_data *d, const heap_key k)
{
    size_t  i;

    if (!h)
        return -1; /* No heap specified. */

    /* Ensure there is room for at least one more entry. */
    if (h->len >= h->max) {
        size_t     max;
        reference *ref;

        /* Minimum size is 15 references; then double up
           to 1966080 entries; then set next multiple of
           1024*1024 + 1024*1024-2. */
        if (h->len < 15)
            max = 15;
        else
        if (h->len < 1966080)
            max = 2 * h->len;
        else
            max = (h->len | 1048575) + 1048574;

        ref = realloc(h->ref, max * sizeof h->ref[0]);
        if (!ref)
            return -2; /* Out of memory; cannot add more. */

        h->max = max; 
        h->ref = ref;
    }

    i = h->len++;
    h->ref[i].key = key;
    h->ref[i].val = data;

    /* Omitted:  Percolate 'i' towards root,
                 keeping the heap order property for keys. */

    /* if (!i) "i is root";
       For all other cases, the parent is at index ((i-1)/2), and
       if (i&1) "i is a left child, sibling is (i+1)";
       else     "i is a right child, sibling is (i-1)";
    */

    return 0;
}

在堆数组中,如果有n 节点,则索引i(根索引为0)的节点有

  • 索引为(i - 1)/2 的父级当且仅当i &gt; 0

  • 当且仅当2*i+1 &lt; n时,索引2*i+1的左孩子

  • 当且仅当2*i+2 &lt; n2*i+2 处的右孩子

k 级别的节点的索引是连续的,从 (1 &lt;&lt; k) - 1(2 &lt;&lt; k) - 2,包括(当根具有索引 0 和级别 0 时)。

索引为i(根索引为0,级别为0)的节点位于k级别,为floor(log2(i+1))或通过例如以下函数获得:

static inline size_t  ith_level(size_t  i)
{
    size_t  n = 0;
    size_t  t = (i + 1) / 2;

    while (t) {
        t >>= 1;
        n++;
    }

    return n;
}

同样,上面示例中的逻辑有效。但是,由于示例代码是在没有经过适当审查的情况下一次性编写的,因此其中可能存在错误。因此,如果您对示例代码或此答案中的任何地方有任何问题,请在评论中告诉我,以便我可以根据需要进行检查和修复。

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多