Find the maximum width of a binary tree?
Short answer: int WidthOfBinaryTree(TreeNode root) { if (root == null) return 0; int maxWidth = 0; Queue<(TreeNode node, int idx)> queue = new Queue<(TreeNode, int)>(); queue.Enqueue((root, 0)); while (queue.Count > 0) { int size = queue.Count; int start = queue.Peek().idx; int end = start; for (int i = 0; i < size; i++) { var (node, idx) = queue.Dequeue(); end = idx; if (node.left != null) queue.Enqueue((node.left, 2 * idx +…
Explain a bit more
1)); if (node.right != null) queue.Enqueue((node.right, 2 * idx + 2)); } maxWidth = Math.Max(maxWidth, end - start + 1); Follow on: } return maxWidth; } Explanation: Assign index to each node as if in a complete tree; width is max difference of indices per level.
Example code
int WidthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int maxWidth = 0; Queue<(TreeNode node, int idx)> queue = new Queue<(TreeNode, int)>(); queue.Enqueue((root, 0)); while (queue.Count > 0) { int size = queue.Count;
int start = queue.Peek().idx;
int end = start;
for (int i = 0; i < size; i++) {
var (node, idx) = queue.Dequeue();
end = idx;
if (node.left != null) queue.Enqueue((node.left, 2 * idx + 1)); if (node.right != null) queue.Enqueue((node.right, 2 * idx + 2)); }
maxWidth = Math.Max(maxWidth, end - start + 1); Follow on: }
return maxWidth;
} Explanation: Assign index to each node as if in a complete tree; width is max difference of indices per level.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png