问题:A Binary Tree is called balanced if, for each node in the tree, the height of its left and right subtrees differ by no more than one. Write a function
int height_if_balanced( Tnode *root )
which returns -1 if the tree is not balanced, and returns the height of the tree, if it is balanced.
代码:
int height_if_balanced( Tnode *root )
{
int leftHeight, rightHeight, heightDiff;
if( root == NULL ) {
return 0; // tree is empty
}
leftHeight = height_if_balanced( root->left );
rightHeight = height_if_balanced( root->right );
if( leftHeight == -1 || rightHeight == -1 ) {
// if either the left or right subtree is unbalanced,
return -1 ; // then the whole tree is unbalanced
}
heightDiff = leftHeight - rightHeight;
if( heightDiff < -1 || heightDiff > 1 ) {
return -1; // tree is unbalanced
}
// tree is balanced, so we return its height
if( heightDiff > 0 ) {
return( leftHeight + 1 );
}
else {
return( rightHeight + 1 );
}
}