Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Depth of Binary Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "111" 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, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5 Constraints: The number of nodes in the tree is in the range [0, 105]. -1000 <= Node.val <= 1000

Explanation

Here's the breakdown of the solution:

  • Breadth-First Search (BFS): Traverse the tree level by level. BFS guarantees that the first leaf node encountered will be at the minimum depth.
  • Depth Tracking: Keep track of the depth of each node as we traverse.
  • Leaf Node Check: For each node, check if it's a leaf (no left and right children). If it is, return the current depth.

  • Runtime Complexity: O(N), where N is the number of nodes in the tree.

  • Storage Complexity: O(W), where W is the maximum width of the tree (in the worst case, a complete binary tree, W can be close to N).

Code

    from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def minDepth(root: TreeNode) -> int:
    if not root:
        return 0

    queue = deque([(root, 1)])  # Store node and its depth

    while queue:
        node, depth = queue.popleft()

        if not node.left and not node.right:
            return depth  # Found a leaf node

        if node.left:
            queue.append((node.left, depth + 1))
        if node.right:
            queue.append((node.right, depth + 1))

    return 0  # Should not reach here in a valid tree

More from this blog

C

Chatmagic blog

2894 posts