PPractick

DSA interview question

Maximum Width of a Binary Tree

Medium · Data structures · Topics: tree, bfs

The problem

A tree renderer needs to know how wide a canvas to allocate, and the width of a level is measured between its leftmost and rightmost nodes, counting the empty positions in between, as if the level belonged to a complete binary tree. Give nodes heap-style positions: root 1, left child 2i, right child 2i + 1. The width of a level is last − first + 1. Positions double with every level, so subtract each level's first position before computing children, which keeps the numbers small.

Example: [1, 3, 2, 5, null, null, 9, 6, null, 7] → 7.

Function signature

int widthOfBinaryTree(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[1, 3, 2, 5, 3, null, 9]4Level 2: 5, 3, _, 9
[1, 3, 2, 5, null, null, 9, 6, null, 7]7Level 3: 6, then 5 gaps, then 7
[1, 3, 2, 5]2
[1]1
[]0

(Confirm: gaps between the end nodes of a level count; the answer fits in a 32-bit int, though raw positions can grow like 2^depth.)

How interviewers phrase it

Clarifying questions to ask

  1. Do null positions between the end nodes count? (Yes.)
  2. Do nulls outside the end nodes count? (No.)
  3. How deep can the tree be? (Up to 3000, so raw positions overflow any integer type without normalisation.)

Follow-ups to expect

  1. "Why heap indices?"
  2. "How do you avoid overflow?"
  3. "Why unsigned arithmetic?"
  4. "DFS version?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in