题目链接:https://leetcode-cn.com/problems/balanced-binary-tree/
难度:简单
描述:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
- 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
题解
思路:
与104.二叉树的最大深度,只需要比较左右子树高度是否平衡即可。
# 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 = rightclass Solution:def isBalanced(self, root: TreeNode) -> bool:def recursion(root):if root is None:return 0left_height = recursion(root.left)if left_height == -1:return -1right_height = recursion(root.right)if right_height == -1:return -1# 若平衡返回以该节点为根的树的高度# 若不平衡返回-1if abs(left_height - right_height) < 2:return max(left_height, right_height) + 1else:return -1return recursion(root) != -1
