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.
分析:判断是不是二叉平衡树,就是比较左右子树的深度,递归实现
class Solution {
public:
int checkdepth(TreeNode *node)
{
if(node == NULL)return 0;
int l = checkdepth(node->left)+1;
int r = checkdepth(node->right)+1;
if((l == 0)||(r == 0)) return -1;
if(l > r)
{
if(l-r > 1)return -1;
else return l;
}
else
{
if(r-l >1)return -1;
else return r;
}
}
bool isBalanced(TreeNode *root) {
if(checkdepth(root) == -1) return false;
else return true;
}
};