给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
自顶向下递归
递归求高度,然后判断根节点和左右子节点是否都是平衡二叉树
时间复杂度为O(nlogn)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Solution: def isBalanced(self, root: TreeNode) -> bool: def height(root): if not root: return 0 if not root.left and not root.right: return 1 return 1 + max(height(root.left), height(root.right)) if not root: return True return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
|
计算高度的时候 顺便判断是否是平衡二叉树
-1表示非平衡二叉树,否则为高度
时间复杂度为O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class Solution: def isBalanced(self, root: TreeNode) -> bool: def height(root): if not root: return 0 if not root.left and not root.right: return 1 left = height(root.left) right = height(root.right) if left == -1 or right == -1 or abs(left-right) > 1: return -1 else: return 1 + max(left, right) return height(root) >= 0
|