110. 平衡二叉树

题目描述

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

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

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

示例 1:

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

    3
   / \
  9  20
    /  \
   15   7

返回 true

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false

我的解法——递归求解(AC)

  • 注意:该递归是从下往上的
# 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 myisBalanced(self, root):
        if(not root):
            return True, 0
        status1, height1 = self.myisBalanced(root.left)
        status2, height2 = self.myisBalanced(root.right)
        max_height = max(height1, height2)
        if(status1 and status2 and abs(height1 - height2) <= 1):
            return True, max_height + 1
        return False, max_height + 1
        
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.myisBalanced(root)[0]