题目描述:
给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:
输入:root = []
输出:true
提示:
- 树中的节点数在范围 [0, 5000] 内
- -104 <= Node.val <= 104
解题思路:
判断一棵二叉树是不是平衡树,当且仅当其所有子树也都是平衡二叉树。因此,可以使用递归的方式判断二叉树是不是平衡二叉树。
代码:
Python代码:
class solution:
def isBalanced(self, root):
def height(self, root):
if max(root.left, root.right) + 1 <= 1:
return 1
else:
return 0
if root is None:
return True
left_height = height(root.left)
right_height = height(root.right)
return self.isBalanced(root.left) and self.isBalanced(root.right) and left_height and right_height
C语言版:
int height(struct TreeNode* root) {
if (root == NULL) {
return 0;
} else {
return fmax(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(struct TreeNode* root) {
if (root == NULL) {
return true;
} else {
return fabs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
复杂度分析:
- 时间复杂度: O ( n 2 ) O(n^2) O(n2),其中 n 是二叉树中的节点个数。
- 空间复杂度:O(n),其中 n是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n。
题目来源: