CodeArchon

hardTreesFacebookAmazonLinkedInMicrosoft

Codec Transceiver

A satellite ground station must beam a hierarchical sensor map down to orbit as a flat telemetry string, then reconstruct it bit-for-bit on the receiver.

Design an algorithm to serialize a binary tree to a string and deserialize that string back into the exact same tree.

Choose approach

1
#0
curr
2
3
4
5
1/12
Narrationstep 1 of 12

Visit Node 1. Append to buffer: "1"

1def serialize(root):
2 out = []
3 def dfs(node):
4 if not node: out.append("N"); return
5 out.append(str(node.val))
6 dfs(node.left); dfs(node.right)
7 dfs(root)
8 return ",".join(out)
9
10def deserialize(data):
11 vals = data.split(",")
12 i = 0
13 def build():
14 nonlocal i
15 if vals[i] == "N":
16 i += 1; return None
17 node = TreeNode(int(vals[i])); i += 1
18 node.left = build()
19 node.right = build()
20 return node
21 return build()
Variables
emit=1
encoded=1

How to think about it

  1. Preorder captures the root first, then recursively left then right.
  2. A null sentinel disambiguates missing children at reconstruction time.
  3. Deserialization uses an advancing index on the token stream.

Edge cases to catch in interview

  • Empty tree -> just the sentinel.
  • Unbalanced tree -> many sentinels appear deep in the stream.

Examples

Example 1"1,2,N,N,3,4,N,N,5,N,N"
{"arr":[1,2,3,null,null,4,5]}
Example 2"N"
{"arr":[]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed