Skip to content
mlmentorship

Serialize and Deserialize Binary Tree

Frame every recursive child slot with a value or null token, rebuild exact topology, and distinguish trusted decoding from complete-stream validation.

Published · 25 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Serialize and Deserialize Binary Tree

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

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

Worked example: null markers preserve the child positions that values alone loseA left child and a right child can share value preorder (1,2). Their null-marked encodings differ and reconstruct distinct shapes.Child positions and missing childrenbelong to the structureTree A: two is on the left12#Encode: 1, 2, #, #, #Tree B: two is on the right1#2Encode: 1, #, 2, #, #
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?
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:

TreeComplete encoding
Root 1, left child 21,2,#,#,#
Root 1, right child 21,#,2,#,#
Pictured four-node tree1,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.
write 1/9; open slots 212##34###
Original real-node inventory
visit 110213243
stream[1]callStackvisit(1)activeStatevisit 1topology1 -> 2, 1 -> 3, 3 -> 4
visit 1
0
stream
[1]
call stack
visit(1)

Recognize it
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

Worked example: null markers preserve the child positions that values alone loseA left child and a right child can share value preorder (1,2). Their null-marked encodings differ and reconstruct distinct shapes.Child positions and missing childrenbelong to the structureTree A: two is on the left12#Encode: 1, 2, #, #, #Tree B: two is on the right1#2Encode: 1, #, 2, #, #
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.
write 1/9; open slots 212##34###
Original real-node inventory
visit 110213243
stream[1]callStackvisit(1)activeStatevisit 1topology1 -> 2, 1 -> 3, 3 -> 4
visit 1
0
stream
[1]
call stack
visit(1)

Recognize it
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


@dataclass
class TreeNode:
   val: int
   left: "TreeNode | None" = None
   right: "TreeNode | None" = None
class TreeCodec:
   def serialize(self, root: TreeNode | None) -> str:
      values: list[str] = []

      def visit(node: TreeNode | None) -> None:
         if node is None:
            values.append("#")
            return
         values.append(str(node.val))
         visit(node.left)
         visit(node.right)

      visit(root)
      return ",".join(values)

   def deserialize(self, data: str) -> TreeNode | None:
      values = iter(data.split(","))

      def build() -> TreeNode | None:
         value = next(values)
         if value == "#":
            return None
         node = TreeNode(int(value))
         node.left = build()
         node.right = build()
         return node

      return build()

Frame Every Recursive Slot

Every call emits one leading token. A null slot stops there; a node token introduces two child slots.

A tree with real nodes has missing child slots, so its encoding contains 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 ; recursive stack space is .

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 , with 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 . Pending slots use space, but token accumulation and the final string still require 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.