037-力扣刷题-110--平衡二叉树--重点进行理解

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

image.png image.png

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def get_height(root):  #递归判断子树是不是平衡树,全部平衡整个才平衡
            if root is None:
                return 0
            left_height,right_height=get_height(root.left),get_height(root.right)  #进行递归的操作


                #return #如何判断ruturn True和False
      #  if left_height != 平衡树 or right_height!= 平衡树 or abs(left_height-height_height) > 1  就不是平衡树那么我们让他返回值是 -1 此时的话,left_height返回的值就是-1也就是说返回值是-1就不是平衡树


            if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1:  #判断两个子树的高度差用abs不用考虑正负
                return -1
            #如果说是平衡树那么应该返回什么呢?
            return max(left_height,right_height)+1  #我们就把最长的数加上 1 3这种情况就是子树最长的深度,因为叶子节点返回的是0所以加一是加的root节点本身
        return (get_height(root) >= 0) #返回的是大于零的数就说明是平衡二叉树