6/22/2020

[LeetCode] 110. Balanced Binary Tree

Problem : https://leetcode.com/problems/balanced-binary-tree/

Use memorization to avoid duplicate calculation of depth.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    @lru_cache(maxsize = None)
    def depth(self, node):
        if node:
            return 1 + max(self.depth(node.left), self.depth(node.right))
        else:
            return 0
    
    def isBalanced(self, root: TreeNode) -> bool:
        if root:
            return self.isBalanced(root.left) and \
                   self.isBalanced(root.right) and \
                   abs(self.depth(root.left) - self.depth(root.right)) <= 1
        
        return True

No comments:

Post a Comment