DSA interview question
Seen from directly above, a binary tree shows exactly one node per horizontal position: the one closest to the top. Place the root at horizontal distance 0, left children at −1 and right children at +1. The top view lists, from the leftmost distance to the rightmost, the first node BFS reaches at each distance. BFS visits nodes level by level, so the first one seen at a distance is the highest, and among nodes on the same level it's the leftmost.
Example: [1, 2, 3, null, 4, null, null, null, 5, null, 6] → [2, 1, 3, 6].
vector<int> topView(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 2, 3] | [2, 1, 3] | |
[10, 20, 30, 40, 60, 90, 100] | [40, 20, 10, 30, 100] | 60 and 90 are hidden under 10 |
[1, 2, 3, null, 4, null, null, null, 5, null, 6] | [2, 1, 3, 6] | 4 and 5 are hidden; 6 sticks out at +2 |
[1] | [1] | |
[] | [] |
(Confirm: horizontal distance: left −1, right +1; for each distance the topmost node wins, and ties on a level go to the one BFS meets first.)
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