Leetcode 662: Maximum Width of Binary Tree

grid47
grid47
Exploring patterns and algorithms
Sep 1, 2024 6 min read

A binary tree where the maximum width is highlighted, with the width softly glowing as it’s measured.
Solution to LeetCode 662: Maximum Width of Binary Tree Problem

You are given the root of a binary tree. Determine the maximum width of the tree, which is defined as the maximum width among all levels. The width of a level is the distance between the leftmost and rightmost non-null nodes, including null nodes in between that would be present in a complete binary tree.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a binary tree represented as an array of integers, where each integer is a node value or null if the node does not exist.
Example: root = [1, 3, 2, 5, 3, null, 9]
Constraints:
• 1 <= number of nodes <= 3000
• -100 <= Node.val <= 100
Output: The output is a single integer representing the maximum width of the binary tree.
Example: 4
Constraints:
• The output is guaranteed to be within the range of a 32-bit signed integer.
Goal: The goal is to compute the maximum width of the binary tree by finding the maximum width across all levels of the tree.
Steps:
• 1. Use a breadth-first search (BFS) approach to traverse the tree level by level.
• 2. At each level, compute the width by calculating the difference between the positions of the leftmost and rightmost non-null nodes.
• 3. Keep track of the maximum width encountered during the traversal.
Goal: The binary tree has at most 3000 nodes, and node values range between -100 and 100.
Steps:
• 1 <= number of nodes <= 3000
• -100 <= Node.val <= 100
Assumptions:
• The binary tree is represented as a complete binary tree with null values for missing nodes.
Input: root = [1, 3, 2, 5, 3, null, 9]
Explanation: The maximum width is at level 3 with the nodes [5, 3, null, 9], which gives a width of 4.

Input: root = [1, 3, 2, 5, null, null, 9, 6, null, 7]
Explanation: The maximum width is at level 4 with the nodes [6, null, null, null, null, null, 7], which gives a width of 7.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus