Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximum Width of Binary Tree

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "662" 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 the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is guaranteed that the answer will in the range of a 32-bit signed integer. Example 1: Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width exists in the third level with length 4 (5,3,null,9). Example 2: Input: root = [1,3,2,5,null,null,9,6,null,7] Output: 7 Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). Example 3: Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width exists in the second level with length 2 (3,2). Constraints: The number of nodes in the tree is in the range [1, 3000]. -100 <= Node.val <= 100

Explanation

Here's the breakdown of the solution:

  • Level-Order Traversal with Indexing: Perform a level-order (breadth-first) traversal of the binary tree. Assign an index to each node based on its position in a complete binary tree. The root has index 1. The left child of a node with index i has index 2*i, and the right child has index 2*i + 1.
  • Width Calculation at Each Level: At each level, the width is calculated as the difference between the largest and smallest indices of the nodes present at that level, plus 1. This accounts for the "null" nodes that would be present in a complete binary tree.
  • Maximum Width Tracking: Keep track of the maximum width encountered so far and update it as we process each level.

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

  • Space Complexity: O(W), where W is the maximum width of the binary tree (maximum number of nodes at any level). In the worst case (complete binary tree), W can be proportional 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 widthOfBinaryTree(root: TreeNode) -> int:
    if not root:
        return 0

    queue = deque([(root, 1)])  # Node, index
    max_width = 0

    while queue:
        level_length = len(queue)
        leftmost_index = queue[0][1]
        rightmost_index = queue[-1][1]

        max_width = max(max_width, rightmost_index - leftmost_index + 1)

        for _ in range(level_length):
            node, index = queue.popleft()

            if node.left:
                queue.append((node.left, 2 * index))
            if node.right:
                queue.append((node.right, 2 * index + 1))

    return max_width

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Maximum Width of Binary Tree