When given a number of nodes we are able to calculate the min depth of the binary tree by doing log2(n)
Where n is the number of nodes.
If you draw the tree out for the maximum depth for example 12 nodes you work out that the maximum depth can only be 4 if the tree is to remained balanced.
0
/ \
0 0
/ \ / \
0 0 0 0
/\ \ \
0 0 0 0
Sorry for the bad ascii art. Does anyone know of a forumla that is able to calculate the max depth of a binary tree when given the number of nodes? Or at least point me in the right direction?
By using the root element :
By using the number of nodes and some math logic (which I definitely cannot express properly (I’m by no means a math guru); but here it is) :
Observation :
Analysis :
2^m = n
ln(2^m) = ln(n)
Conclusion :
Now, if m = 2,… , then the maximum depth is 2. Just get the int part of it. 😉
NOTE: I’m definitely re-inventing the wheel here; but that’s probably part of the fun of dealing with something you know nothing about; and doing it, solely following your instinct and observations… 🙂