给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
返回 false 。
思路:使用递归法,进行 左右中 (后序遍历)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if self.get_height(root) == -1:
return False
return True
def get_height(self, root: TreeNode) -> int:
if not root:
return 0
left_height = self.get_height(root.left)
right_height = self.get_height(root.right)
if left_height == -1:
return -1
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return 1+max(left_height, right_height)