Left and Right View of a Binary Tree Using BFS and DFS
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests understanding of binary tree traversal by computing boundary nodes at each depth using both breadth-first and depth-first strategies.
You are given a binary tree encoded as a level-order list where null marks missing children. Your task is to extract two views of the tree:
- Left view: For each depth, the leftmost node at that depth.
- Right view: For each depth, the rightmost node at that depth.
Both views are lists indexed by depth, starting from depth 0 (the root).
Your solution must compute both views using two different methods—a breadth-first search (BFS) and a depth-first search (DFS)—then verify that both methods produce identical results.
Input Format
The input follows standard level-order encoding:
level_order[0]is the root.- For any node at list index
i, its left child appears at index2*i+1and its right child at index2*i+2, provided those indices exist in the list. - A
nullentry means no node exists at that position but still occupies an index slot.
For example, [1, 2, null, 3, null, 4] means:
- Root is 1
- Left child of 1 is 2, right child of 1 is
null(missing) - Left child of 2 is 3, right child of 2 is
null - Left child of 3 is 4
This produces a left-skewed tree: 1 → 2 → 3 → 4.
Output Format
Return [left_view, right_view] where:
left_view[d]is the value of the leftmost node at depthd.right_view[d]is the value of the rightmost node at depthd.
If the input is empty or the root is null, return [[], []].
Key Rules
- Leftmost/rightmost means spatial position within the level, not "follow left/right pointers." For example, in the tree
[1, 2, 3, 4], node 4 hangs off the left subtree but is still the rightmost node at depth 2 because it is the only node at that depth. - When a level has only one node, that node appears in both views.
- Both BFS and DFS must produce the same results; your function should assert this before returning.
Constraints
0 <= len(level_order) <= 10^5- Node values are integers (may be negative, zero, or positive).
- The tree may be empty, skewed, balanced, or irregular.
- You must implement both BFS and DFS traversals and verify they match.
Examples
Example 1
Input: compute_tree_views([1, 2, 3, 4, 5, None, 6])
Output: [[1, 2, 4], [1, 3, 6]]
Example 2
Input: compute_tree_views([1])
Output: [[1], [1]]
Example 3
Input: compute_tree_views([1, 2, None, 3, None, 4])
Output: [[1, 2, 3, 4], [1, 2, 3, 4]]
Example 4
Input: compute_tree_views([1, None, 2, None, 3])
Output: [[1, 2, 3], [1, 2, 3]]
Hints
Hint 1
For BFS, snapshot the queue size before processing each level—the first and last nodes dequeued in that batch define the left and right boundaries.
Hint 2
For DFS, carry a depth parameter and append a node's value only when depth equals the current length of the view list, ensuring you capture the first node reached at each depth.
Hint 3
Reconstruct the tree using a queue: dequeue a parent, then read the next two list slots as its children, enqueuing only non-null children.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to identify the leftmost and rightmost nodes at every depth of a binary tree, implementing the solution using both breadth-first (level-order) and depth-first traversal techniques.
Step 1: Reconstruct the Tree
The input is a level-order list where null entries represent missing children. We rebuild the tree using a queue-based algorithm:
- Create the root from the first element.
- Dequeue a parent node and consume the next two list positions as its left and right children.
- Enqueue only the children that are not
null. - A
nullentry consumes an index but never becomes a parent itself.
This correctly handles irregular trees like [1, null, 2, null, 3], which forms a right-skewed chain.
Step 2: BFS Solution
Process the tree one level at a time:
- Snapshot the current queue size—this tells us how many nodes belong to the current depth.
- Dequeue exactly that many nodes, appending their children (left before right) to the queue.
- The first node dequeued is the leftmost at this depth; the last is the rightmost.
Why this works: By recording the queue size before processing, we cleanly separate one depth from the next. Children are always enqueued after their level's nodes. Since we enqueue left children before right children and process parents left-to-right, each level appears in the queue in true spatial left-to-right order. The first and last positions therefore give us the correct boundaries.
Step 3: DFS Solution
Perform a preorder traversal while tracking depth. Record a node only when depth == len(view), meaning this is the first node we've encountered at this depth.
- Left view: Visit left children before right. Using an explicit stack (to avoid recursion depth limits), push the right child first, then the left, so the left pops first.
- Right view: Reverse the order—push left first, then right, so right pops first.
Why this works: In a left-first preorder traversal, nodes at the same depth are visited in left-to-right spatial order. Consider two nodes at the same depth: their lowest common ancestor has one in its left subtree and one in its right. Preorder fully explores the left subtree before entering the right, so the first node reached at any depth is the leftmost. The equality check ensures we record each depth exactly once, on first arrival.
We use explicit stacks instead of recursion to handle deep trees (up to 10^5 nodes) without exceeding Python's default recursion limit.
Complexity
Let n be the number of nodes and h the tree height.
- Time: O(n) to build the tree, O(n) for BFS, O(n) for DFS. Each node is visited a constant number of times.
- Space:
- Tree construction: O(w) where w is the maximum width of any level (up to ~n/2 for complete trees).
- BFS: O(w) queue space.
- DFS: O(h) stack space (O(log n) when balanced, O(n) when skewed).
Both output lists have length h+1, where h is the maximum depth.
Solution Code
from collections import deque
from typing import List, Optional
def compute_tree_views(level_order: List[Optional[int]]) -> List[List[int]]:
if not level_order or level_order[0] is None:
return [[], []]
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Reconstruct the tree from level-order encoding
root = TreeNode(level_order[0])
q = deque([root])
idx = 1
while q and idx < len(level_order):
parent = q.popleft()
# Process left child
if idx < len(level_order) and level_order[idx] is not None:
parent.left = TreeNode(level_order[idx])
q.append(parent.left)
idx += 1
# Process right child
if idx < len(level_order) and level_order[idx] is not None:
parent.right = TreeNode(level_order[idx])
q.append(parent.right)
idx += 1
# BFS: process tree level by level
left_bfs = []
right_bfs = []
q = deque([root])
while q:
level_size = len(q)
for position in range(level_size):
node = q.popleft()
if position == 0:
left_bfs.append(node.val)
if position == level_size - 1:
right_bfs.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
# DFS for left view: visit left subtree before right
left_dfs = []
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
if depth == len(left_dfs):
left_dfs.append(node.val)
# Push right first so left is popped first
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
# DFS for right view: visit right subtree before left
right_dfs = []
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
if depth == len(right_dfs):
right_dfs.append(node.val)
# Push left first so right is popped first
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
# Verify both methods agree
assert left_bfs == left_dfs
assert right_bfs == right_dfs
return [left_bfs, right_bfs]