HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

What is the size of the Perfect binary tree with n nodes in last level

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
nodesthelastwhatwithsizelevelperfectbinarytree

Problem

I want to know how to calculate total number of nodes in a perfect balanced binary tree with $n$ nodes in the last level. I know the answer is $2\cdot 2^{\log n} - 1$. Just curious how this can be calculated

Solution

A perfect (binary) tree of depth $k$ has exactly $2^{k+1}−1$ nodes.

There are probably several ways to prove it. A simple way is by induction.
Each level has twice as many nodes as the previous level (since each node has exactly 2 children in a binary tree). The base level - the root - has 1 nodes. Note that the root is depth 0, not 1.

Let's denote the number of nodes in level $i$ by $N_i$. We know,

$N_0 =1$

$N_i = 2N_{i-1} = 2^{i}$

The total amount of nodes (of tree of depth $k$) is $S_k \equiv N_1 + N_2 + \cdots + N_k$, that is,

$$ S_k = 1 + 2 + 4 + 8 + \ldots +2^{k}.$$
This is a geometric series, whose sum is $S_k = 2^{k+1}-1$.

Now for your question:

We are given a perfect (binary) tree with $n$ nodes at the last level, how many nodes does it have overall?

We are given that at the last level (call it level $k$) we have $N_k=2^k=n$ nodes. Then $k=\log_2 n$ and we get that $S_k=2^{k+1}-1=2n-1$; Yes, each level has one more node than the entire tree above it.

A related question:

we are given a perfect (binary) tree with $n$ nodes, what is its depth?

Now we are given that the total number of nodes is $S_k = 2^{k+1}-1 = n$, thus $k=\log_2 (n+1)-1$ (again, the root is considered depth 0 here).

Context

StackExchange Computer Science Q#13621, answer score: 5

Revisions (0)

No revisions yet.