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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool JudgeTree(TreeNode* p, int& depth)
{
if(p==NULL) //注意结束条件,不是p->left或p->right
{
depth =0; //这句可以不要
return true;
}
int nLeftDepth=0;
int nRightDepth=0;
if(JudgeTree(p->left, nLeftDepth) && JudgeTree(p->right, nRightDepth))
{
int nDif=nLeftDepth-nRightDepth;
if(nDif<=1 && nDif>=-1)
{
//depth要赋值
depth = nLeftDepth > nRightDepth ? (nLeftDepth+1):(nRightDepth+1);
return true;
}
}
return false;
}
bool isBalanced(TreeNode *root) {
if(root==NULL)
{
return true;
}
TreeNode* pTemp=root;
int nDepth=0;
return JudgeTree(pTemp, nDepth);
}
};