DSA interview question
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.
int widthOfBinaryTree(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 3, 2, 5, 3, null, 9] | 4 | Level 2: 5, 3, _, 9 |
[1, 3, 2, 5, null, null, 9, 6, null, 7] | 7 | Level 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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in