Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Balanced Binary Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "110" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a binary tree, determine if it is height-balanced. Example 1: Input: root = [3,9,20,null,null,15,7] Output: true Example 2: Input: root = [1,2,2,3,3,null,null,4,4] Output: false Example 3: Input: root = [] Output: true Constraints: The number of nodes in the tree is in the range [0, 5000]. -104 <= Node.val <= 104

Explanation

Here's the solution to determine if a binary tree is height-balanced:

  • High-Level Approach:

    • Use a recursive depth-first search (DFS) to traverse the tree.
    • For each node, calculate the heights of its left and right subtrees.
    • Check if the absolute difference between the heights is at most 1. If it is not, the tree is not balanced. Also, recursively check if the left and right subtrees are balanced.
  • Complexity:

    • Runtime: O(N), where N is the number of nodes in the tree.
    • Storage: O(H), where H is the height of the tree (due to the call stack in recursion). In the worst case (skewed tree), H = N, so the space complexity can be O(N). In the best case (balanced tree), H = log N, so the space complexity can be O(log N).

Code

    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: TreeNode) -> bool:

        def height(node):
            if not node:
                return 0
            return 1 + max(height(node.left), height(node.right))

        def is_balanced_helper(node):
            if not node:
                return True

            left_height = height(node.left)
            right_height = height(node.right)

            if abs(left_height - right_height) > 1:
                return False

            return is_balanced_helper(node.left) and is_balanced_helper(node.right)

        return is_balanced_helper(root)

More from this blog

C

Chatmagic blog

2894 posts