这里说的堆(heap)是一种 nearly complete binary tree:除了最低的一层外,其它层填充满了结点,并且最底层的结点是从左到右填充的。
这里假定root结点的索引从1 开始。
它有如下的性质:
1. 对于一个包含 n个元素的heap, 它的高度为 floor(lg n)
证明: 用 h表示这个heap的高度。则有:
2^h <= n <= 2^(h+1) -1 < 2^(h+1)
对上面取对数:
h < = lgn < h + 1
考虑到 h为整数, h只能是 floor(lg n).
2. 对于以数组形式存储的 n个元素的heap, 叶子结点的索引为 floor(n/2)+1, floor(n/2)+2, ..., n
证明: 假定叶子结点索引为 floor(n/2), 那么, 2 * floor(n/2) < n, 表示这个叶子节点存在子结点。。,也就是它不是叶子结点。
2 * (floor(n/2)+1) =2 * floor(n/2) + 2 > n, 不存在子节点,所以,索引为 floor(n/2)+1的结点是叶子结点。
3. n个元素的heap, 它的叶子结点的个数为 ceiling[n/2]
证明: 根据 2可以得出这个结论。
4. 对于 n个元素的heap, 最多有ceiling(n/2^(h+1))个高度为h的结点
证明 i: 用归纳法。
当 h = 0时的结点为叶子结点,根据3, 个数为 ceiling(n/2) = ceiling(n/2^(h+1)(当 h = 0).
所以, h =0时成立。
假定 h-1时成立,那么此时高度 h-1的结点个数为 ceiling(n/2^(h-1)).
那么, 考虑去掉所有叶子结点的heap T'.它的节点数为 n - ceiling[n/2] = floor(n/2).
在原来堆中高度为 h的结点在 T'中对应的高度为 h-1.
那么在原来堆中高度h的结点的个数等于 T'中高度为 h-1的个数:
ceiling( floor(n/2)/2^(h-1)) <= ceiling((n/2)/2^(h-1)) = ceiling(n/2^h).
证明 ii:
假定结点 i高度为 h,那么, i, i*2, i*4, ..., i*2^h 为 i的最长路径,并且 i*2^(h+1) > n.
于是有,
i*2^h <= n < i * 2^(h+1)
i > n/2^(h+1), i < 2 * (n/2^(h+1))
所以, i的取值为, ceiling(n/2^(h+1)), ceiling(n/2^(h+1)) + 1, ..., ceiling(n/2^(h+1)) + ceiling(n/2^(h+1)) - 1
共有 ceiling(n/2^(h+1)) 个。
参考:
1.
http://www2.cs.sfu.ca/CourseCentral/307/petra/2009/SLN_2.pdf
2.
http://blog.csdn.net/wdq347/article/details/8822741
3.