首先判断一颗二叉树是否平衡,我们需要知道左子树深度与右子树的深度之差是否小于等于1,
其次我们需要判断他的左子树是否平衡,右子树是否平衡,
而求子树的深度,我们可以用到之前所写的求树的深度的代码
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
return abs(depth(root->left) - depth(root->right)) < 2 && isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root){
if(root == NULL) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
};