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 :
int maxHeight(BinaryTree *p) {
if (!p) return 0;
int left_height = maxHeight(p->left);
int right_height = maxHeight(p->right);
return (left_height > right_height) ? left_height + 1 : right_height + 1;
}
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 :
- m => max Depth (actual the INT part of the depth, discard any decimal places)
n => number of nodes
ln => natural logarithm (=log[e])
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... :-)