Recursive Python solution


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
    
        def helper(self,root):
            if not root:
                return 0
            leftht = self.helper(root.left)
            if leftht == -1:
                return -1
            rightht = self.helper(root.right)
            if rightht == -1:
                return -1
            if abs(leftht-rightht) > 1:
                return -1
            return max(leftht,rightht)+1
            
        def isBalanced(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if self.helper(root) == -1:
                return False
            return True
            
            
    

Log in to reply
 

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