题目描述:给定一个二叉树,判断它是否是高度平衡的二叉树
解题思路:(1)判断根节点是否为0 (2)计算出左右子树的高度 (3)比较左右子树的绝对值是否超过一
代码:
class Solution {
public:
int height(TreeNode *root) {
if(root == NULL)return 0;
return max(height(root->left), height(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL)return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(height(root->left) - height(root->right)) <= 1;
}
};