Take the 2-minute tour ×
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It's 100% free, no registration required.

This question assumes the definition of a complete binary tree to be:

A binary tree $T$ with $N$ levels is complete if all levels except possibly the last are completely full, and the last level has all its nodes to the left side.

The following is an excerpt from Algorithms:

It ($\log N$) is also the depth of a complete binary tree with $N$ nodes. (More precisely: $⌊\log N⌋$.)

Why is the above excerpt valid?

Originally defined here

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

Consider how a complete binary tree of height $h$ is constructed, one vertex at the root level, two at the first level below the root, four at the second level below, and so on, until the $h^{th}$ level, which has at least one vertex, but at most twice as many as the previous level. Note that the number of vertices at each level is a power of two (excluding the last, which is a special case). Then we have: $$ 1+\sum_{i=0}^{h-1}2^{i} \leq n \leq \sum_{i=0}^{h}2^{i} $$ Using the identity that the sum of the first $k$ powers of two is $2^{k+1}-1$ we get: $$ 1+2^{h}-1 \leq n \leq 2^{h+1}-1\\ 2^{h} \leq n \leq 2^{h+1}-1 $$ and hence $$ 2^{h} \leq n < 2^{h+1} $$

Taking the base 2 logarithm: $$ h \leq \log n < h+1 $$ So we can conclude $$h = \lfloor\log n\rfloor$$ As $\log n$ is bigger than $h$, but less than the next integer $h+1$.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.