Coding questions · Meta
Compute left and right views once
This question evaluates understanding of binary tree traversal, depth tracking, and view computation for left and right perspectives, plus the ability to implement a concurrent single-pass traversal while handling edge cases such as empty trees and duplicate keys.
Given the root of a binary search tree, output two lists: the nodes visible from the left side and the nodes visible from the right side, from top to bottom. Implement a single-pass traversal that computes both views concurrently. Discuss iterative vs. recursive strategies, how you track depth and first/last-at-depth nodes, and analyze time/space complexity. Handle empty trees and trees with duplicate keys.
Left and Right Views of a Binary Tree in One Pass
Given the root of a binary tree, return two lists: the left view (the first node seen at each depth, scanning top to bottom) and the right view (the last node seen at each depth). Compute BOTH views in a single traversal.
The tree is provided as a LeetCode-style level-order array level_order, where each element is a node value or null (None) to denote a missing child. Reconstruct the tree, then traverse it once.
Return the answer as a list of two lists: [left_view, right_view].
A single level-order BFS works naturally: at each level the first dequeued node is on the left edge and the last is on the right edge. Empty trees return [[], []]. Duplicate keys are allowed and are emitted by value (a single-node level contributes its value to both views).
Example: for [1, 2, 3, 4, null, null, 5] the left view is [1, 2, 4] and the right view is [1, 3, 5], so the answer is [[1, 2, 4], [1, 3, 5]].
Constraints
- 0 <= number of nodes <= 10^4
- Node values fit in a 32-bit signed integer
- Duplicate node values are allowed
- The tree may be empty (level_order is empty or begins with None)
- Must compute both views in a single traversal of the tree
Hints
- A level-order BFS gives you the views for free: at each level, the first node you dequeue is the leftmost (left view) and the last is the rightmost (right view).
- Snapshot the queue size at the start of each level so you know which dequeue index is first (i == 0) and which is last (i == n-1).
- When the tree is a single chain (only-left or only-right children), every level has exactly one node, so the left and right views are identical.
- A recursive DFS also works: pass the current depth, and for the left view record the first value reached at each new depth (preorder, left-first); for the right view record the first value reached visiting right-first.