Preorder records each node and each missing child, so the decoder can consume one token per recursive slot and recover the exact topology.
Problem trace
Null markers preserve branching that value order alone cannot determine
Read it this way:A left child and a right child can share value preorder (1,2). Their null-marked encodings differ and reconstruct distinct shapes. Which encoding token tells the decoder that the second tree has no left child?
Sources and provenance
Full interview answer 25 min read
Convert a binary tree to text and rebuild an independent tree with exactly the same values and structure.
Problem
Input. Serialization receives a finite integer-valued binary tree; deserialization receives complete text produced by the matching serializer.
Output. Serialization returns a string. Deserialization returns newly created nodes with the original values and child positions.
Rules. Duplicate and negative values are allowed, but cycles and shared children are not.
Preserve the source tree. Missing left and right children must remain distinguishable.
An empty tree must round-trip as None; original object identities need not survive.
The reference assumes trusted, complete serialized input rather than validating arbitrary text.
Example. A root 1 with left child 2 and no right child must rebuild with that same missing-right structure.
Rebuilding root 1 with only a right child 2 would be incorrect despite preserving both values.
Picture
Preorder values 1,2 describe either a left child or a right child. Null markers distinguish them:
Tree
Complete encoding
Root 1, left child 2
1,2,#,#,#
Root 1, right child 2
1,#,2,#,#
Pictured four-node tree
1,2,#,#,3,4,#,#,#
Empty tree
#
For each node, emit its value, then its complete left stream, then its complete right stream.
Problem trace
Null markers preserve branching that value order alone cannot determine
Input and goalConvert a tree to text and rebuild the same tree from that text.
Initialize preorder at the rootVisit root 1 and append its value. Its left child is 2; its right child is 3.
Use structural sentinels when a tree must round-trip through a linear stream and node values alone do not uniquely identify its shape.
Keep true
Each recursive serialize call emits exactly one leading token for its slot, and each deserialize call consumes exactly one leading token before recursively rebuilding the same left and right slots.
Reuse it
To encode recursive structure linearly, emit a token for every recursive slot, including empty ones, and make the decoder consume tokens in the identical traversal order.
Visit root 1 and append its value. Its left child is 2; its right child is 3. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which two null tokens close node 2? Why could the value order 1,2,3,4 alone not determine the tree?
Reference drawing
Problem trace
Null markers preserve branching that value order alone cannot determine
Execution trace
Input and goalConvert a tree to text and rebuild the same tree from that text.
Initialize preorder at the rootVisit root 1 and append its value. Its left child is 2; its right child is 3.
Use structural sentinels when a tree must round-trip through a linear stream and node values alone do not uniquely identify its shape.
Keep true
Each recursive serialize call emits exactly one leading token for its slot, and each deserialize call consumes exactly one leading token before recursively rebuilding the same left and right slots.
Reuse it
To encode recursive structure linearly, emit a token for every recursive slot, including empty ones, and make the decoder consume tokens in the identical traversal order.
Visit root 1 and append its value. Its left child is 2; its right child is 3. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which two null tokens close node 2? Why could the value order 1,2,3,4 alone not determine the tree?
Read it this way:A left child and a right child can share value preorder (1,2). Their null-marked encodings differ and reconstruct distinct shapes. Which encoding token tells the decoder that the second tree has no left child?
Code
Use this node type for a local run.
from dataclasses import dataclass@dataclassclass TreeNode: val: int left: "TreeNode | None" = None right: "TreeNode | None" = None
Every call emits one leading token. A null slot stops there; a node token introduces two child slots.
A tree with n real nodes has n+1 missing child slots, so its encoding contains 2n+1 tokens.
The decoder mirrors those calls. Reading a node’s leading token does not finish that subtree; its two child streams still follow.
State the Trust Boundary
The source decoder trusts its producer. Missing tokens can raise StopIteration; trailing tokens are silently ignored.
For example, decoding #,# returns an empty tree without checking the extra marker.
With bounded-size integer tokens, time and output storage are O(n); recursive stack space is O(h).
For larger integers, account for text length and conversion costs too. Deep trees can exceed Python’s recursion limit.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why is # not optional punctuation? It tells the next call which child slot is empty.
Validate the Whole Stream
Choose this when: Missing, trailing or malformed tokens must fail instead of being trusted.
Track position explicitly. Require a token for each requested slot, then require exhaustion after the root returns.
def deserialize_tree_checked(data): values, position = data.split(","), 0 def build(): nonlocal position if position == len(values): raise ValueError("missing slot") value = values[position] position += 1 if value == "#": return None node = TreeNode(int(value)) node.left, node.right = build(), build() return node root = build() if position != len(values): raise ValueError("trailing tokens") return root
Both 1,# and #,# raise ValueError, for different reasons. The nine-token fixture reconstructs the exact pictured topology.
This uses Python’s integer parser, not a canonical-spelling test. For example, +1,#,# is accepted and re-encodes without the plus sign.
The decoder still splits all input and uses recursion. Add explicit text-size, depth and integer-digit limits before accepting untrusted production input.
For bounded-size tokens, time and retained token/output storage are O(n), with O(h) stack space.
Encode with an Explicit Slot Stack
Choose this when: Encoder recursion depth is the controlling limit, but the exact wire format must stay unchanged.
def serialize_tree_iterative(root): values, pending = [], [root] while pending: node = pending.pop() if node is None: values.append("#") else: values.append(str(node.val)) pending.extend((node.right, node.left)) return ",".join(values)
Push right before left because the last pushed slot is processed next. Every null still emits a token.
The fixture produces the same nine-token bytes; empty input produces #. The input tree remains unchanged.
For bounded-size tokens, time is O(n). Pending slots use O(h) space, but token accumulation and the final string still require O(n) storage.
This removes recursive encoder calls only. The reference and checked decoders still have their depth limits.
Check Framing without Building Nodes
Start with one open slot. Each token consumes one; a nonnull token adds two.
Reject a token arriving after slots reach zero, and require exactly zero slots at the end. Integer token grammar needs separate validation.