A simple python solution (72ms, 7 lines)


  • 0
    C

    trick:

    Ba_height() will return the height of the tree if it is balanced, or None if it is not balanced.

    Therefore, we can just check Ba_height(root)!=None

    def isBalanced(self, root):
        def Ba_height(node):
            if not node:
                return 0
            l,r = Ba_height(node.left), Ba_height(node.right)
            if l!=None and r!=None and abs(l-r)<=1:
                return 1+max(l,r)
        return Ba_height(root)!=None
    

    Note:
    1. Since the height could be 0, we have to write if `l!=None and r!=None...` instead of `if l and r ...`
    2. Alternatively, all those `!=None` can be replaces with `>=0`

  • 0
    Y

    you can simplify this code

    if l!=None and r!=None and abs(l-r)<=1:
    

    to

    if l and r and abs(l-r)<=1

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.