110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
左右子树高度差不大于1,并且子树本身也是平衡树。
size_t MaxDepth(struct TreeNode* root) {
return root == NULL ? 0
: 1 + fmax(MaxDepth(root->left), MaxDepth(root->right));
}
bool isBalanced(struct TreeNode* root) {
if (root != NULL) {
size_t leftHeight = MaxDepth(root->left);
size_t rightHeight = MaxDepth(root->right);
return abs(leftHeight - rightHeight) <= 1
&& isBalanced(root->left) && isBalanced(root->right);
}
return true;
}