Implement tree left/right views via BFS and DFS
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of binary tree traversal techniques and algorithmic reasoning for producing per-depth left and right views, assessing competencies in data structures, traversal ordering, and correctness across edge cases.
Constraints
- 0 <= number of nodes <= 10^4
- Node values fit in a 32-bit signed integer
- Tree is given in level order with null/None markers; children of a null entry are omitted
- An empty tree returns two empty lists
Examples
Input: ([1, 2, 3, 4, 5, None, 6],)
Expected Output: ([1, 2, 4], [1, 3, 6])
Explanation: Balanced-ish tree: level 0 -> [1], level 1 -> [2,3], level 2 -> [4,5,6]. Leftmost per level = 1,2,4; rightmost = 1,3,6.
Input: ([],)
Expected Output: ([], [])
Explanation: Empty tree: both views are empty.
Input: ([7],)
Expected Output: ([7], [7])
Explanation: Single node: it is both the leftmost and rightmost node of its only level.
Input: ([1, 2, None, 3, None, 4],)
Expected Output: ([1, 2, 3, 4], [1, 2, 3, 4])
Explanation: Left-skewed chain 1->2->3->4. Each level has exactly one node, so left and right views are identical.
Input: ([1, None, 2, None, 3],)
Expected Output: ([1, 2, 3], [1, 2, 3])
Explanation: Right-skewed chain 1->2->3. One node per level, so both views match.
Input: ([1, 2, 3],)
Expected Output: ([1, 2], [1, 3])
Explanation: Root with two children: level 0 -> [1], level 1 -> [2,3]. Left view 1,2; right view 1,3.
Hints
- BFS: process the tree one level at a time. The first node you pop for a level is its left-view node; the last is its right-view node.
- DFS: recurse with the current depth. For the left view, recurse into the left child before the right and append a node's value only the first time you reach a given depth (len(view) == depth). For the right view, recurse right-first.
- Both views always have the same length — exactly the height of the tree — because every level contributes exactly one node to each view.
- Watch the edge cases: an empty tree yields two empty lists, and any skewed tree yields identical left and right views (one node per level).