Skip to content
AI360Xpert
Beta
Difficulty: HardTrees

Serialize and Deserialize Binary Tree

Problem in Plain English

Design a codec that converts any binary tree into a single string and rebuilds the exact original tree, including its shape, from that string. An empty tree must round-trip back to null.

Problem Statement

Implement serialize(root) to encode a binary tree as one string and deserialize(data) to rebuild the same values and left/right structure. The format is your choice; the array notation in the examples describes the tree, not a required serialized string.

An empty tree must round-trip to an empty tree. Assume the decoder receives strings produced by its matching encoder. The implementations below leave the input tree unchanged and allocate fresh nodes on every decode. Node values may repeat, so values cannot identify child positions.

Constraints

  • The tree contains between 00 and 10410^4 nodes, inclusive.
  • Each node value is an integer in [−1000,1000][-1000,1000].
  • No particular serialization format is required; each decoder must invert its matching encoder.

Examples

Example 1

Input
root = [1,2,3,null,null,4,5]
Output
[1,2,3,null,null,4,5]

Node 1 has children 2 and 3; node 2 is a leaf; node 3 has children 4 and 5. Level order writes 1,2,3,N,N,4,5,N,N,N,N; preorder writes 1,2,N,N,3,4,N,N,5,N,N. Either matching decoder reconstructs the displayed tree, including both missing children of 2.

Example 2

Input
root = []
Output
[]

Both encoders below write N for a missing root. The decoder reads that marker and returns null without allocating a node.

Example 3

Input
root = [0,null,-1000,0,1000]
Output
[0,null,-1000,0,1000]

The root has no left child and a right child valued -1000, whose children are 0 and 1000. Explicit markers preserve the asymmetric shape; commas keep the negative and multi-digit values separate; the repeated zero is another node, not a reference to the root.

Intuition

Values alone cannot describe a tree: a root with a left child and a root with a right child would otherwise look identical. Write a token for each value and a distinct N token for each absent child. In Example 1, the two absent children of 2 must appear before the children of 3 in level order, or immediately after 2 in preorder. A decoder following the same traversal can then put every value into exactly one child slot.

Approaches

Level Order Codec

Solution Details

Reveal Level Order Codec: intuition, complexity, and code

Hints

Hint 1
Distinguish a missing child from a node whose value is zero; a separate N marker carries shape.
Hint 2
Use a comma delimiter so negative and multi-digit integers can be read as complete tokens.
Hint 3
A breadth-first decoder consumes two tokens per real parent. A preorder decoder finishes a child subtree before resuming its parent.
Hint 4
For preorder without recursion, track each unfinished parent and its next child side; push right before left when encoding.

Edge Cases

  • An absent root encodes as N in both versions and decodes without allocating nodes.
  • A single node writes its value and two markers; repeated values must still allocate distinct node objects.
  • Left-only and right-only chains require markers on opposite sides. A 10,000-node chain must work without changing recursion limits.
  • Zero, -1000 and 1000 are valid values. Negative signs and multiple digits are preserved by comma-separated tokens.
  • Calling deserialize twice on the same string produces equal shapes with disjoint node identities; changing one result must not change the other or the original.

Common Mistakes and Interview Tips

  • Dropping null markers: [1,2] and [1,null,2] would become indistinguishable.
  • Treating a zero value as an absent node. Test the node reference, not its numeric value.
  • Using Java ArrayDeque to store null positions: it rejects null entries. The encoder below uses LinkedList for nullable positions.
  • Using JavaScript shift repeatedly, slicing the remaining tokens per subtree, or repeatedly concatenating growing immutable strings can introduce quadratic work.
  • Pushing left before right during iterative preorder reverses the intended order. A stack pops the last pushed item first.
  • Advancing an ancestor to its next child only after visiting a descendant misaligns tokens. Update or pop the parent frame before pushing a real child.
  • Keeping tokens or cursor fields across calls can leak state. Assuming recursion survives a maximum-depth chain can fail despite a correct recurrence.
  • Mixing codec formats: the breadth-first string and preorder string require their corresponding decoders; accepting malformed arbitrary strings is outside this contract.

Key Takeaway

Lossless tree encoding needs a traversal order plus explicit structure markers. Reconstruct with the same order and a queue of parents or stack of unfinished child slots. A linear traversal becomes a linear codec only when string building and token consumption also avoid repeated copying.