题目描述

iShot20220507 下午8.02.47.png

代码实现

class Solution {
    func isBalanced(_ root: TreeNode?) -> Bool {
        if root == nil { return true }
        return abs(maxDepth(root?.left) - maxDepth(root?.right)) <= 1 && isBalanced(root?.left) && isBalanced(root?.right)
    }

    func maxDepth(_ root: TreeNode?) -> Int {
        if root ==  nil { return 0 }
        return max(maxDepth(root?.left), maxDepth(root?.right)) + 1
    }
}

Q.E.D.