Skip to content

Latest commit

 

History

History
34 lines (26 loc) · 880 Bytes

File metadata and controls

34 lines (26 loc) · 880 Bytes

110. Balanced Binary Tree

Difficulty: Easy

URL

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

Solution

Approach 1: Recursion

The code is shown below:

# 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:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def getHeight(root):
            if not root:
                return 0
            return max(getHeight(root.left), getHeight(root.right)) + 1
        
        if not root:
            return True
        left_height, right_height = getHeight(root.left), getHeight(root.right)
        diff = abs(left_height - right_height)
        return diff <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)