Thursday 29 December 2011

How would you check if a binary tree is balanced?


How would you check if a binary tree is balanced?
Solution:


A tree is considered balanced when the difference between the min depth and max depth does not exceed 1.
Recursive algorithms always work well on trees, so here’s some code.


int min_depth( Node * root )
{
    if( !root )
    {
        return 0;
    }
    return 1 + min( min_depth( root->left ),min_depth( root->right ));
}
int max_depth( Node * root )
{
    if( !root )
    {
        return 0;
    }
    return 1 + max( max_depth( root->left ),max_depth( root->right ));
} 

bool is_balanced( Node * root )
{
    return ( max_depth( root ) - min_depth( root ) ) <= 1
}

No comments:

Post a Comment