PPractick

DSA interview question

Top View of a Binary Tree

Medium · Data structures · Topics: tree, bfs, hash map

The problem

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].

Function signature

vector<int> topView(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[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.)

How interviewers phrase it

Clarifying questions to ask

  1. How is horizontal distance defined? (The root is 0; left −1; right +1.)
  2. How are ties on the same level broken? (The first one in BFS order.)
  3. In what order should the output be? (From the leftmost to the rightmost distance.)

Follow-ups to expect

  1. "Why BFS, not DFS?"
  2. "How do you order the output?"
  3. "What changes for the bottom view?"
  4. "Can DFS work?"
  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