Leftmost and Rightmost Nodes per Depth from a Serialized Tree
Trees & GraphsAuto-graded · 17 test casesLast updated
Given a level-order serialized binary tree, return the first and last node value at each depth, testing BFS over an array-encoded tree and careful handling of null slots.
Silhouettes of a Binary Tree
You are given a binary tree encoded as a flat list in level-order form. Your task is to compute what is visible when the tree is looked at from its left edge and from its right edge.
Input encoding
The parameter tree is a list whose entries are integers or None:
- The first entry is the root. If it is
None(or the list is empty), the tree is empty. - Going through the non-null nodes in breadth-first order (top to bottom, left to right), each one takes the next two unread entries of the list as its left child and right child, in that order. A
Noneentry means that child is absent. - A
Noneentry does not take up any further entries for children of its own. - Trailing
Noneentries may be left out. If the list ends before a node's child slots are filled, those missing children are absent.
For example, [1, 2, 3, None, 5, None, 4] describes this tree:
1
/ \
2 3
\ \
5 4
Task
Return a list of two lists, [left_view, right_view]:
left_viewholds, for every depth from the root downward, the value of the leftmost node at that depth.right_viewholds, for every depth from the root downward, the value of the rightmost node at that depth.
Both lists are ordered from the top level to the bottom level. The leftmost node of a level is the one that appears first when that level is read left to right, regardless of whether it is a left or right child of its parent. If a level contains only one node, that value appears in both lists.
For an empty tree, return [[], []].
Constraints
- The number of nodes in the tree is between
0and100. - Each node value is between
-100and100. - The tree may be empty, a single node, or fully skewed (all left or all right children).
- The returned value must be a list containing exactly two lists: the left view first, then the right view.
Examples
Example 1
Input: tree_silhouettes([1, 2, 3, None, 5, None, 4])
Output: [[1, 2, 5], [1, 3, 4]]
Example 2
Input: tree_silhouettes([1, None, 3])
Output: [[1, 3], [1, 3]]
Hints
Hint 1
The node you see from the left at a given depth is the first node of that level when read left to right; from the right it is the last one.
Hint 2
Run a breadth-first traversal one level at a time, taking a snapshot of the queue size at the start of each level so you know where the level ends.
Hint 3
You do not need to build node objects: keep a pointer into the input list and, each time you dequeue a non-null value, read the next two entries as its children (treating entries beyond the end of the list as absent).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
At each depth, the node visible from the left is the first node of that level and the node visible from the right is the last. So a level-order traversal that records the first and last value of every level gives both views.
We do not need to construct tree nodes. The serialization lists children in exactly the order a BFS visits their parents, so we can run the BFS directly on values while a pointer pos walks through the input list:
- If the list is empty or its first entry is
None, return[[], []]. - Start the queue with the root value and set
pos = 1. - For each level, fix
size = len(queue)before processing so this level is separated from the next. - For each dequeued value, record it as the left view entry if it is the first in its level, and as the right view entry if it is the last.
- Read the next two entries from the list (if any remain) as the node's left and right children, advancing
poseach time. Enqueue only non-null children.
Why it is correct
- Pointer stays in sync: the serialization gives child slots only to non-null nodes, in BFS order. The queue holds only non-null values and dequeues them in exactly that order, so the next two unread entries always belong to the node just dequeued. Bounds checks treat omitted trailing entries as absent children.
- Levels are separated: capturing the queue size before the inner loop means each iteration handles exactly one depth, left to right.
- Views are right: the first and last node of a level are the leftmost and rightmost at that depth, whether they are left or right children. A single-node level has first equal to last, so it appears in both views.
Complexity
- Time: O(n), each list entry is read once and each node is enqueued and dequeued once.
- Space: O(w) for the queue, where w is the maximum width of the tree (at most O(n)), plus O(h) for the output.
Reference solution
from collections import deque
from typing import List, Optional
def tree_silhouettes(tree: List[Optional[int]]) -> List[List[int]]:
if not tree or tree[0] is None:
return [[], []]
queue = deque([tree[0]])
pos = 1
n = len(tree)
left_view = []
right_view = []
while queue:
size = len(queue)
for i in range(size):
value = queue.popleft()
if i == 0:
left_view.append(value)
if i == size - 1:
right_view.append(value)
for _ in range(2):
if pos < n:
child = tree[pos]
pos += 1
if child is not None:
queue.append(child)
return [left_view, right_view]