Left and right views of a binary tree
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen and at Amazon, last asked Sep 2025. It tests trees, bfs and dfs.
Given a binary tree, return its left view and its right view. The left view lists, for every depth from the root down, the leftmost node at that depth. The right view lists the rightmost node at each depth. Solve it twice: once with breadth-first search and once with depth-first search that tracks the depth, then dry-run both on the edge cases below.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
views(root: TreeNode | None) -> tuple[list[int], list[int]]— returns(left_view, right_view).TreeNodehasval,leftandright. - In the examples the tree is written in level order, with
Nonefor a missing child.
Example
[1, 2, 3, 4, 5, None, 6] -> ([1, 2, 4], [1, 3, 6])
[] -> ([], [])
[7] -> ([7], [7])
[1, 2, None, 3, None, 4] -> ([1, 2, 3, 4], [1, 2, 3, 4]) # left-skewed: one node per level
Constraints
-
0 <= number of nodes <= 10^4; values fit in a 32-bit signed integer. - The tree may be skewed, so recursion depth can reach the number of nodes.
Clarifying questions
- Does the right view mean the rightmost node per level, even if it hangs off the left subtree?
- Should both views be returned together or by separate functions?
- How deep can the tree be: is recursion acceptable, or should DFS be iterative?
What a strong answer covers
- BFS by level: the first node of each level goes into the left view and the last into the right view. O(n) time, O(width) space.
- DFS carrying the depth: visit left before right and record a node when its depth is reached for the first time (
len(view) == depth); visit right first for the right view. O(n) time, O(height) space. - Why both views always have the same length, the height of the tree.
- Dry runs on an empty tree, a single node, left- and right-skewed trees and a balanced tree, and the stack risk on a skewed tree.
Follow-ups
- Return the top and bottom views (by horizontal distance from the root).
- Return the boundary of the tree in anticlockwise order.
- Make the DFS iterative with an explicit stack.
Where it's asked
- Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
- Amazon · Coding · Last asked Aug 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.

