你如何证明在n个节点的二进制堆中有ceil(n / 2)叶?

时间:2016-11-17 21:54:41

标签: algorithm data-structures binary-heap

如何证明具有n个节点的二进制堆具有正好⌈n/2⌉叶节点?

4 个答案:

答案 0 :(得分:4)

Let x be the height of tree in which case 2^x = no of leaves
=> 2^0 + 2^1+ 2^2 + 2^3 +...2^x = n
=> 2^(x+1) - 1 = n (By sum series power of 2 formula)
=>2^(x+1)= n+1
=> log(n+1) = x+1
=>log(n+1)-1 = x;
=>log(n+1)- log2 =x
x =log(n+1/2)

=> no of leaves = (n+1)/2 (which is 2^(log(n+1/2))

答案 1 :(得分:1)

对此的一个很好的直觉是以归纳的方式思考这个问题。对于n = 0的情况,没有任何叶子,对于n = 1的情况,根是唯一的叶子。对于之后添加的每个节点,它要么(1)将一个子节点添加到以前是叶子的节点,现在有一个子节点,不改变叶子节点的数量,或者(2)将子节点添加到已经存在的节点一个孩子,将叶子的数量增加一个。使用归纳法,您可以将其形式化,以证明二进制堆中的叶数是⌈n/2⌉。

答案 2 :(得分:0)

假设我们有n个节点

0-level
1-level
...
d-level                          // Total 2^d nodes at this level. #ofLeafNodes at this level depends on how many nodes are there at below level. 
last-level-containing-X-nodes    // All leaf nodes

叶子节点只能来自最后两个级别。

最后一级有x个叶子节点。 而倒数第二级将具有总共2 ^ d个节点和⌈x/2⌉叶节点。

因此,总叶子节点=

= (Leaf nodes at bottom-most level) + (Leaf nodes at second bottom-most level) 
= (x + (2^d - ⌈x / 2⌉))                 //Equation 1

二进制堆树中的总节点数=>

n       = (2^(d + 1) - 1) + x
2*(2^d) = n-x+1
2^d     = (n-x+1)/2

现在将2^d替换为上面的eq#1,

(x + (2^d - ⌈x / 2⌉))
=(x + (n-x+1)/2 - ⌈x / 2⌉)
= n/2 + x/2 + 1/2 - ⌈x / 2⌉

对于偶数nx将是奇数:

= n/2 + x/2 + 1/2 - (x/2 + 1/2)
= n/2 + x/2 + 1/2 - x/2 - 1/2
= n/2
= ⌈n / 2⌉        /*Since n is even*/

对于奇数nx将是偶数:

= n/2 + x/2 + 1/2 - (x/2 + 1/2)
= n/2 + x/2 + 1/2 - x/2
= n/2 + 1/2 
= ⌈n / 2⌉

答案 3 :(得分:0)

要解决这个问题,我们需要找到堆的最后一个内部节点和第一个叶节点。

从堆属性,我们知道一个索引为 i 的节点,

Parent[i] = ceil(i/2)
Left[i]   = 2i
Right[i]  = 2i+1

假设最后一个内部节点在 floor(n/2),第一个叶子节点在 floor(n/2)+1。

Right[floor(n/2)]
=   2(floor(n/2)) + 1
<=  2 * (n-(2-1))/2 + 1
=   2 * (n-1)/2 + 1
=   n

从 Right[ floor(n/2) ] <= n,我们知道 floor(n/2) 将在堆的边界内有一个右孩子,因此,它是最后一个内部节点。此外, floor(n/2) 之前的所有节点都将是在堆边界内具有右孩子的内部节点。然后,我们知道内部节点的索引是 1, 2, 3, 4, ... floor(n/2),这意味着最后一个内部节点的索引是堆中的内部节点数。

Left[floor(n/2) + 1]
=   2 * (floor(n/2) + 1)
>   2 * (n/2 - 1 + 1)
=   2 * n/2
=   n

从Left[ floor(n/2)+1] <= n,我们知道floor(n/2)+1会有一个离开堆边界的左孩子,因此,它是第一个叶子节点.此外, floor(n/2)+1 之后的所有节点都将有一个超出堆边界的左子节点。那么,我们知道在 floor(n/2) 之后的节点(最后一个内部节点),在堆中不会有子节点,所以它们都是由 floor(n/2)+1, floor(n/ 2)+2, 楼层(n/2)+3, ... n.

因此,从上面我们知道:

number of leaves = element of heap - number of internal nodes
                 = n - floor(n/2)
                 = ceil(n/2)