level 1
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
就是按照定义来,有点优化在实现上
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height( TreeNode * ptr )
{
if( !ptr )
{
return 0;
}
int a = height( ptr->left );
if( a == -1 )
{
return a;
}
int b = height( ptr->right );
if( b == -1 )
{
return b;
}
if( abs( a- b ) > 1 )
{
return -1;
}
return max( a, b ) + 1;
}
bool isBalanced(TreeNode* root) {
return height( root ) != -1;
}
};
2017年09月18日 16点09分