Leetcode 110. Balanced Binary Tree

Description: Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Link: 110. Balanced Binary Tree

Example:

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true

Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:
Input: root = []
Output: true

思路: 递归判断每个节点的左右子树的深度是否相差小于等于1.

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        if abs(self.treedepth(root.left) - self.treedepth(root.right)) > 1:
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)
    
    def treedepth(self, root):
        if not root: return 0
        return 1 + max(self.treedepth(root.left), self.treedepth(root.right))

日路: 2021-03-17  今天没有全力以赴地学习,那就归咎于天阴吧...

原文地址:https://www.cnblogs.com/wangyuxia/p/14552289.html