A binary tree is said to be height balanced if both its left sub-tree & right sub-tree are balanced and the difference between the height of left sub-tree and right sub-tree is less than or equal to 1.
i have to find out if a given binary tree is balanced or not!
based on the above concept i have used the following code:
bool isbalanced(struct node *root)
{
int left,right;
if(root==NULL)
return true;
else
{
left=height(root->left);
right=height(root->right);
if(abs(left-right)<=1 && isbalanced(root->right)==true && isbalanced(root->left)==true)
return true;
else
{
return false;
}
}
}
I have calculated the height using a separate height() function:
int height(struct node *root)
{
if(root==NULL)
return 0;
int left=height(root->left);
int right=height(root->right);
if(left>right)
return 1+left;
else
return 1+right;
}
I am getting the correct solution if the tree is balanced or unbalanced. But if the given tree is skewed the time complexity would be O(n^2).
Can there be a method so that i can accomplish this task in a more efficient way?