思路很清晰,就是获得每个节点的左右子树高度,然后返回 abs(左子树高度-右子树高度) <= 1的值。
return self.eachNodeBalanced(root) and self.isBalanced(root.left) and self.isBalanced(root.right)
这句代码就是返回每个节点是否满足平衡二叉树调节的布尔值的与值,只要有一个是False,那么最终的返回值都是False,只有当所有的节点都满足平衡条件时,最终结果才是True。
完整代码如下:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root is None:
return True
return self.eachNodeBalanced(root) and self.isBalanced(root.left) and self.isBalanced(root.right)
def getHeight(self, root):
if root is None or root.val is None:
return 0
return max(self.getHeight(root.left), self.getHeight(root.right)) + 1
def eachNodeBalanced(self, root):
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
return abs(leftHeight - rightHeight) <= 1