Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the height of a complete binary tree with N nodes?

What is the height of a complete binary tree with N nodes? I'm looking for an exact answer, and either a floor or ceiling value.

like image 447
Karim Elsheikh Avatar asked Nov 27 '22 14:11

Karim Elsheikh


1 Answers

It's CEIL(log2(n+1))-1

  • 1 node gives log2(2) = 1
  • 3 nodes gives log2(4) = 2
  • 7 nodes gives log2(8) = 3
  • 15 nodes gives log2(16) = 4
    ...

EDIT: According to wikipedia, the root node (rather un-intuitively?) does not count in the height, so the formula would be CEIL(log2(n+1))-1.

like image 83
Joachim Isaksson Avatar answered Dec 05 '22 12:12

Joachim Isaksson