Friday, 15 July 2011

Check if Binary tree is balanced.


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