https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/description/
平衡二叉树特点:左右子树的深度差不超过1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// 计算每个结点的左右子树高度差
int height(TreeNode *root)
{
if(root == nullptr)
{
return 0;
}
else
{
return max(height(root->left),height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root)
{
if(root == nullptr)
{
return true;
}
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); // 判断root结点是否平衡,然后递归判断左右子树各个结点是否平衡
}
};