天天看点

力扣(leetcode) 110. 平衡二叉树

题目在这:​​https://leetcode-cn.com/problems/balanced-binary-tree/​​

思路分析:

其实这跟前两天求最大深度的代码一样,就加一行就行了。

递归左子树,然后递归右子树,当左子树减去右子树的绝对值大于1的时候,返回False。

完整代码:

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        self.temp = True
        def depth(root):
            if root == None:
                return 0
            left_hight = depth(root.left)
            right_hight = depth(root.right)
            if abs(left_hight - right_hight) >1:
                self.temp = False
            return max(left_hight,right_hight) + 1
        depth(root)
        return self.temp