The original problem is:
Define the height of a binary tree to be the number of nodes in the longest path from the root to a leaf. The empty tree is considered to have height 0. A node is k-balanced if its left and right subtrees differ in height by at most k. A tree is k-balanced if all of its nodes are k-balanced. The empty tree is considered to be k-balanced.
For example, the tree below has height 4.
o / \ o o / \ o o / o
This tree is 2-balanced but not 1-balanced, because the left subtree of the root has height 3 and the right subtree of the root has height 1. Your task is to write a method that takes a balance factor k and a number of nodes n and returns the maximum height of a k-balanced tree with n nodes.
One of the answer(right and fast) is:
int fewest_node(int k,int h)
{
if(h <= 0)
return 0;
return 1+fewest_node(k,h-1)+fewest_node(k,h-1-k);
}
int maxHeight2(int k, int n)
{
for(int h = 1;;h++)
if(fewest_node(k,h) > n)
return h - 1;
}
and my solution(terribly slow) is:
int maxHeight(int k, int n)
{
int i,left,right;
if(k >= n)
return n;
if(n > 2)
{
left = maxHeight(k,n-1);
if(left <= k)
return left+1;
else
{
i = n - 2;
left = maxHeight(k,i);
right = maxHeight(k,n-1-i);
while((left - right) > k)
{
i--;
left = maxHeight(k,i);
right = maxHeight(k,n-1-i);
}
return left+1;
}
}
else
return n;
}
My question:
Is my solution really correct? I mean, does it work regardless of its efficiency? Or in other words, is it right logically? (BTW, I think it's right, and I have tested the output when
n
is less than 30)Why is my solution so slow? As you can see, I'm a newbie to DSA.