Edge Silhouettes of a Level-Order Binary Tree
Trees & GraphsAuto-graded · 23 test casesLast updated
Build a binary tree from a level-order list with gaps and report the first and last node of every level, testing BFS level separation and level-order parsing.
You are given a binary tree encoded as a list in level-order (breadth-first) form. Each entry is either an integer value or None, which marks an absent child.
Encoding
- The first entry is the root. If it is
None, the tree is empty. - Going through the list in order, every real (non-
None) node takes the next two unused entries as its left child and right child, in that order. The nodes are handled in the same order they appear in the list. - A
Noneentry occupies a slot but is not a node, so it never receives children of its own. - Trailing
Noneentries may be left out. If the list ends before a node's child slots are filled, the missing children are simply absent.
Task
Write a function that returns a list of two lists, [left_silhouette, right_silhouette]:
left_silhouette: for each depth from the root downward, the value of the leftmost node at that depth.right_silhouette: for each depth from the root downward, the value of the rightmost node at that depth.
"Leftmost" and "rightmost" are determined by position within a level, not by which type of edge leads to the node. A right child can be the leftmost node of its level if nothing lies to its left at that depth.
Both lists are ordered from the root level to the deepest level. A level with exactly one node contributes that node's value to both lists.
If the tree is empty (the list is empty or its first entry is None), return [[], []].
Your solution should obtain both lists from a single traversal of the tree. Values may repeat, and the result depends only on node positions, not on value ordering, so the tree need not be a search tree.
Constraints
0 <= len(level_order) <= 10^4- Each entry is an integer or
None. - Values may repeat; do not use values to identify nodes.
- The input is a valid level-order encoding as described above.
- Return exactly
[left_silhouette, right_silhouette].
Examples
Example 1
Input: level_edge_views([1, 2, 3, 4, 5, 6, 7])
Output: [[1, 2, 4], [1, 3, 7]]
Example 2
Input: level_edge_views([1, 2, 3, None, 4, None, 5])
Output: [[1, 2, 4], [1, 3, 5]]
Example 3
Input: level_edge_views([1, 1, 1, 1])
Output: [[1, 1, 1], [1, 1, 1]]
Hints
Hint 1
For a single level, which node do you see first when walking left to right, and which one last? Think about processing the tree one whole level at a time.
Hint 2
Before handling a level, record how many nodes are currently waiting in the queue. That count marks exactly where this level ends and the next begins, so no explicit depth counter is needed.
Hint 3
The input list is consumed in the same order BFS visits real nodes. Keep a pointer into the list and hand each dequeued node the next two slots as children, enqueueing only the non-None ones.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the tree one level at a time with a queue, while reading the input list with a moving pointer.
- If the list is empty or starts with
None, return[[], []]. - Put the root in a queue and set a pointer
index = 1to the next unread slot of the list. - While the queue is not empty, take
level_size = len(queue). That is exactly the number of nodes at the current depth. - Pop
level_sizenodes. The first one popped is the leftmost node of the level and the last one popped is the rightmost. Append them to the left and right results respectively. - For each popped node, read the next two slots from the list as its left and right children. A
Noneslot is consumed but not enqueued; a real value is enqueued for the next level.
Both results come from the same single pass, and no explicit tree structure or depth counter is needed.
Why it is correct
- Level invariant: at the start of each outer iteration the queue contains exactly the real nodes of one depth, in left-to-right order. Initially this holds for the root. Because each node's left child is enqueued before its right child, and nodes are processed left to right, the next depth is also enqueued in left-to-right order. Only
level_sizenodes are popped per iteration, so nodes of the next depth are never mixed in. - First and last: given that order, the first popped node of a level is the leftmost and the last popped is the rightmost. A one-node level is both.
- Child assignment: in a level-order encoding, children appear in the same order as their non-null parents. BFS dequeues real nodes in that same order, so the shared pointer always gives each node its own two slots.
Noneslots are never enqueued, so they correctly never receive children. - Duplicates: only positions matter, and the queue holds one entry per node occurrence, so equal values never collide.
Complexity
- Time: O(n), where n is the length of the list. Each slot is read once and each real node is enqueued and dequeued once.
- Space: O(w) for the queue, where w is the maximum width of the tree, plus the output of size O(h) for each view.
A recursive preorder DFS that carries the depth would also work, but on a very skewed tree it risks hitting Python's recursion limit, and the input format makes BFS the natural fit.
Reference solution
from collections import deque
from typing import List, Optional
def level_edge_views(tree_nodes: List[Optional[int]]) -> List[List[int]]:
if not tree_nodes or tree_nodes[0] is None:
return [[], []]
n = len(tree_nodes)
left_view: List[int] = []
right_view: List[int] = []
# Queue holds values of real nodes on the current frontier.
queue = deque([tree_nodes[0]])
index = 1 # next unread slot in the input list
while queue:
level_size = len(queue)
for i in range(level_size):
value = queue.popleft()
if i == 0:
left_view.append(value)
if i == level_size - 1:
right_view.append(value)
# Read the next two slots as this node's left and right children.
for _ in range(2):
if index < n:
child = tree_nodes[index]
index += 1
if child is not None:
queue.append(child)
return [left_view, right_view]