Share my easy understanding python solution with explanation


  • 2
    class Solution(object):
        def search(self, root):
            # if we find the tree not height-balanced or the current
            # subtree's height is 0, stop search and return 0
            if not self.balanced or not root:
                return 0
    
            left = self.search(root.left)  # left subtree's height
            right = self.search(root.right)  # right subtree's height
    
            if abs(left - right) > 1:  # if it's not height-balanced
                self.balanced = False
    
            # return current node's height
            return max(left, right) + 1
    
        def isBalanced(self, root):
            self.balanced = True
            self.search(root)
            return self.balanced

Log in to reply
 

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