Balanced Binary Tree – Python 3 (Week 14 – 12)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
not_balance = -1

class Solution:
    """
    @param root: The root of binary tree.
    @return: True if this Binary tree is Balanced, or false.
    """
    
    
    def isBalanced(self, root):
        # write your code here
        return self.maxDepth(root) != not_balance
        
        
    def maxDepth(self, root):
        if not root:
            return 0
        
        left = self.maxDepth(root.left)
        right = self.maxDepth(root.right)
        
        if left == not_balance or right == not_balance:
            return not_balance
        
        if abs(left - right) > 1:
            return not_balance
        
        return max(left, right) + 1

Time, Space O(d).

Leave a comment

Design a site like this with WordPress.com
Get started