Collect Binary Tree Node Values in Left-Root-Right Order
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests binary tree traversal using an explicit stack to visit nodes in left-root-right sequence from a level-order serialized input.
You are given a binary tree represented as a level-order serialized list, where None entries indicate missing children. Your task is to return the values of all nodes visited in left-root-right order (also called in-order traversal).
Level-Order Serialization Format:
The input list contains node values row by row from top to bottom, left to right. Each node in the list must be assigned exactly two child slots (left and right) from subsequent positions in the list, consuming them in order. A None value in a child slot means that position has no node—it is consumed but creates no node, and therefore has no children of its own to place in the list.
For example, [1, None, 2, 3] represents:
1
\
2
/
3
Here's how the deserialization works:
- Index 0: Create node with value
1, enqueue it - Process node
1: its left child is index 1 (None, so no node created), its right child is index 2 (create node2, enqueue it) - Process node
2: its left child is index 3 (create node3, enqueue it), its right child is index 4 (out of bounds, soNone) - Process node
3: no more indices available, both children areNone
Node 3 is the left child of node 2, not a child of the missing left child of node 1, because a None entry creates no node and therefore consumes no child slots from the list.
In-Order Traversal:
For each node, visit all nodes in its left subtree first, then the node itself, then all nodes in its right subtree. This produces a left-root-right ordering.
Your function must:
- Reconstruct the tree from the serialized format
- Traverse it to collect node values in left-root-right order
- Return the collected values as a list
Constraints:
0 ≤ tree.length ≤ 10⁴-1000 ≤ tree[i] ≤ 1000whentree[i]is notNone- The input represents a valid binary tree in level-order format
- Node values may be zero, negative, or duplicated
- An empty list or
[None]represents an empty tree and should return an empty list
Examples
Example 1
Input: collect_inorder_values([1, None, 2, 3])
Output: [1, 3, 2]
Example 2
Input: collect_inorder_values([1, 2, 3, 4, 5, None, 7])
Output: [4, 2, 5, 1, 3, 7]
Example 3
Input: collect_inorder_values([])
Output: []
Example 4
Input: collect_inorder_values([1])
Output: [1]
Hints
Hint 1
First build the tree by consuming pairs of children for each node in a queue. A None entry is consumed but creates no node to enqueue.
Hint 2
For the traversal, simulate the call stack explicitly: push nodes while going left, pop when you can't go further left, emit the value, then move right.
Hint 3
The loop continues while either the current pointer is non-null or the stack has nodes remaining.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has two phases: reconstructing the tree from its serialized form, then collecting values during a left-root-right traversal.
Phase 1: Tree Reconstruction
The input uses level-order format where nodes appear row by row. We maintain a queue of nodes that need their children assigned. Starting with the root (index 0), we process each node by consuming the next two list positions as its left and right children.
Crucially: when a position contains None, we consume that index but create no node, meaning no node is added to the queue. When a position contains a value, we create a node and enqueue it so it can later receive its own children.
For [1, None, 2, 3]:
- Index 0: Create node
1, enqueue it, advance index to 1 - Dequeue node
1: index 1 isNone(no left child), advance to 2; index 2 is2(create and enqueue node2as right child), advance to 3 - Dequeue node
2: index 3 is3(create and enqueue node3as left child), advance to 4 (out of bounds, no right child) - Queue is now empty or we've exhausted the list
This produces: node 1 with only right child 2, which has only left child 3.
Phase 2: Left-Root-Right Traversal
We use an explicit stack to simulate recursive traversal. The algorithm:
- Starting from the root, push nodes onto the stack while descending left as far as possible
- When we can't go left anymore, pop a node from the stack—its entire left subtree has been visited
- Record that node's value
- Move to its right child and repeat from step 1
The loop condition current is not None or stack ensures we continue processing even when current becomes None, as long as unvisited nodes remain on the stack.
Why This Works
The stack holds ancestors whose left subtrees are currently being explored but which haven't been emitted yet. When we pop a node:
- Its left subtree is completely processed (we descended left from it and exhausted all possibilities)
- The node itself hasn't been emitted yet
- Its right subtree hasn't been explored
After recording the node's value, we move to its right child. This ensures the right subtree is fully explored before we pop the next node from the stack (which is an ancestor). This ordering guarantees left-root-right sequence.
Edge Cases
- Empty input
[]or[None]returns[] - Single-node tree
[1]returns[1] - Left-skewed or right-skewed trees create deep stacks but process correctly
- Node values of
0require checkingis not Nonerather than truthiness
Complexity
- Time: O(n) where n is the length of the input list. Each list position is examined once during reconstruction, and each created node is pushed and popped exactly once during traversal.
- Space: O(n) for the reconstructed tree nodes. The traversal stack uses O(h) space where h is tree height (O(log n) for balanced trees, O(n) for skewed trees). The output list is O(m) where m is the number of nodes, but is typically not counted as auxiliary space.
from collections import deque
from typing import List, Optional
def collect_inorder_values(tree: List[Optional[int]]) -> List[int]:
"""Return node values of a binary tree in left-root-right traversal order.
The tree is given as a level-order serialized list where None indicates
a missing child position.
"""
if not tree or tree[0] is None:
return []
class Node:
__slots__ = ("value", "left", "right")
def __init__(self, value):
self.value = value
self.left = None
self.right = None
root = Node(tree[0])
queue = deque([root])
index = 1
while queue and index < len(tree):
node = queue.popleft()
if index < len(tree) and tree[index] is not None:
node.left = Node(tree[index])
queue.append(node.left)
index += 1
if index < len(tree) and tree[index] is not None:
node.right = Node(tree[index])
queue.append(node.right)
index += 1
result = []
stack = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.value)
current = current.right
return result