Simple and efficient python solution


  • 1
    M
    class Solution(object):
        def dfs(self, root):
            if not root: return 0
            
            d1 = self.dfs(root.left)
            if d1 == -1: return -1
            
            d2 = self.dfs(root.right)
            if d2 == -1: return -1
            
            return -1 if abs(d1 - d2) > 1 else max(d1, d2) + 1
        
        def isBalanced(self, root):
            return self.dfs(root) != -1
    

    'dfs' returns -1 if the tree is unbalanced, otherwise returns the depth of the tree


Log in to reply
 

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