Reputation: 3794
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?
Upvotes: 1
Views: 8874
Reputation: 21
The simplest answer looks like this:
int getMaxDepth(Node node)
{
if(node == null) {
return 0;
}
int leftDepth = 1 + getMaxDepth(node.left);
int rightDepth = 1 + getMaxDepth(node.right);
return left > right ? left : right;
}
The concept explained
Upvotes: 2
Reputation: 11
Let no of nodes given(n)=15 Formula is- log2n (log n base 2) now take a max value which must be less than 15 and must be a power result of 2. As here 15 is given the no will be 8. Now, n=8 log2(8)= 3 ,which is our required answer
Upvotes: 1
Reputation: 22810
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... :-)
Upvotes: 3