PPractick

DSA interview question

Right and Left Views of a Binary Tree

Medium · Data structures · Topics: tree, dfs, bfs

The problem

A photographer shoots a tree sculpture from the right side and then from the left side. From the right, each level shows its rightmost node; from the left, its leftmost. A DFS that tracks depth captures either view in one pass. For the right view, visit the right child before the left; the first node reached at each new depth is the visible one. For the left view, visit left first.

Example: [1, 2, 3, null, 5, null, 4] → right view [1, 3, 4], left view [1, 2, 5].

Function signature

vector<int> rightSideView(TreeNode* root);
vector<int> leftSideView(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[1, 2, 3, null, 5, null, 4]right [1, 3, 4] left [1, 2, 5]
[1, 2, 3, 4]right [1, 3, 4] left [1, 2, 4]4 shows from both sides
[1, null, 3]right [1, 3] left [1, 3]
[1, 2]right [1, 2] left [1, 2]
[]right [] left []

(Confirm: one node per level, top to bottom; a node hidden behind others on its level isn't visible.)

How interviewers phrase it

Clarifying questions to ask

  1. Top to bottom order? (Yes.)
  2. Is the rightmost node of each level visible even if it's in the left subtree? (Yes, as with 5 in the first example's left view, or 4 in the second example's right view.)
  3. Can the tree be empty?

Follow-ups to expect

  1. "DFS approach?"
  2. "BFS approach?"
  3. "Why does the visit order matter for DFS?"
  4. "How does this relate to top and bottom views?"
  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