Simple and easy to understand recursive solution for C++


#1

int height_of_tree(TreeNode* node)
{
if(node==NULL)
{
return 0;
}
else
{
int left_height=height_of_tree(node->left);
int right_height=height_of_tree(node->right);
if(left_height==-1 || right_height==-1)
{
return -1;
}
if(abs(left_height-right_height)>1)
{
return -1;
}
else
{
return 1+max(left_height,right_height);
}
}
}
int Solution::isBalanced(TreeNode* A) {
int x=height_of_tree(A);
if(x==-1)
{
return 0;
}
else
{
return 1;
}
}