Fast Python Solution using Exceptions


  • 1
    D

    Faster than 93% of Python submissions

    class UnbalancedTree(BaseException):
        pass
    
    class Solution(object):
        def get_height(self, root):
            if not root:
                return 0
            left = self.get_height(root.left)
            right = self.get_height(root.right)
            if abs(left - right) > 1:
                raise UnbalancedTree() 
            return max(left, right) + 1
            
        def isBalanced(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            try:
                self.get_height(root)
            except UnbalancedTree:
                return False
            return True

Log in to reply
 

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