MAX-HEAPIFY(2/3n的疑惑)

Q:

In CLRS, third Edition, on page 155, it is given that in MAX-HEAPIFY,

The children’s subtrees each have size at most 2n/3—the worst case occurs when the bottom level of the tree is exactly half full.

I understand why it is worst when the bottom level of the tree is exactly half full. And it is also answered in this question worst case in MAX-HEAPIFY

My question is how to get 2n/3?

Why if the bottom level is half full, then the size of the child tree is up to 2n/3?

How to calculate that?

 

A:

For a complete binary tree of height h, number of nodes is f(h) = 2^h - 1. In above case we have nearly complete binary tree with bottom half full. We can visualize this as collection of root + left complete tree + right complete tree. If height of original tree is h, then height of left is h - 1 and right is h - 2. So equation becomes

n = 1 + f(h-1) + f(h-2) (1)

We want to solve above for f(h-1) expressed as in terms of n

f(h-2) = 2^(h-2) - 1 = (2^(h-1)-1+1)/2 - 1 = (f(h-1) - 1)/2 (2)

Using above in (1) we have

n = 1 + f(h-1) + (f(h-1) - 1)/2 = 1/2 + 3*f(h-1)/2

=> f(h-1) = 2*(n-1/2)/3

Hence O(2n/3)

 

 

你可能感兴趣的:(heap)