class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = -1;
return IsBalanced(pRoot,&depth);
}
bool IsBalanced(TreeNode* pRoot,int *depth){
if(pRoot == NULL){
*depth = 0;
return true;
}
int left = -1;
int right = -1;
if(IsBalanced(pRoot->left,&left) && IsBalanced(pRoot->right,&right)){
int diff = left - right;
if(diff <= 1 && diff >= -1){
*depth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
};
没有专门利用 TreeDepth 函数 来递归计算二叉树的深度,而是在计算二叉树深度的同时来判断是否平衡。