Clean Python Solution


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

  • 0
    This post is deleted!

  • 2
    Z

    Very concise, but too many recursions.
    This solution first check if the root node is balanced, then check its subtrees.
    However, if one of its sub tree is unbalanced, we can stop.

    Which means, in the height function, if abs( height of left - height of right)>1, just raise Exception and catch it in the isBalanced.


Log in to reply
 

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