Code to check if the tree is balanced:
int maxDepth(struct Tree *node)
{
if(node == NULL) return 0;
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
return leftDepth > rightDepth ?
leftDepth + 1 : rightDepth + 1;
}
int minDepth(struct Tree *node)
{
if(node == NULL) return 0;
int leftDepth = minDepth(node->left);
int rightDepth = minDepth(node->right);
return leftDepth < rightDepth ?
leftDepth + 1 : rightDepth + 1;
}
bool isBalanced(struct Tree *node)
{
if(maxDepth(node)-minDepth(node) <= 1)
return true;
else
return false;
}
For complete code and other tree operations refer: click here
int maxDepth(struct Tree *node)
{
if(node == NULL) return 0;
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
return leftDepth > rightDepth ?
leftDepth + 1 : rightDepth + 1;
}
int minDepth(struct Tree *node)
{
if(node == NULL) return 0;
int leftDepth = minDepth(node->left);
int rightDepth = minDepth(node->right);
return leftDepth < rightDepth ?
leftDepth + 1 : rightDepth + 1;
}
bool isBalanced(struct Tree *node)
{
if(maxDepth(node)-minDepth(node) <= 1)
return true;
else
return false;
}
For complete code and other tree operations refer: click here
No comments:
Post a Comment