题目:
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 ofevery node never differ by more than 1.
分析:递归遍历,叶子节点的深度为0。
代码如下:
bool key;
int isbalance(TreeNode *root)
{
if(root==NULL)return 0;
int nleft=isbalance(root->left);
int nright=isbalance(root->right);
if(nleft-nright>1||nleft-nright<-1)
{
key=false;
return -1;
}
int max=nleft>nright?nleft:nright;
return max+1;
}
bool isBalanced(TreeNode *root) {
key=true;
isbalance(root);
return key;
}