简单题
直接递归,通过子树的平衡性及高度得到当前节点的平衡性。
时间花费还是比较大,但是懒得再优化。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height(TreeNode* root){
//返回节点的高
if(!root) return 0;
if(!root->left && !root->right) return 1;
return max(height(root->left),height(root->right))+1;
}
bool isBalanced(TreeNode* root) {
//平衡检测
if(!root) return true;
return (isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left)-height(root->right)) <= 1); //左子树平衡,右子树平衡并且高度差不超过1
}
};