Skip to content
Decoder

Serialize and Deserialize Binary Tree

Hard

Problem

Write two functions:

- serialize(root) turns a binary tree into a single string. - deserialize(data) takes that string and rebuilds the exact same tree (same shape, same values).

You choose the string format. The only rule is that deserialize(serialize(root)) must give back an identical tree for any tree, including the empty tree and trees with negative or repeated values.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
serialize([1, 2, 3, null, null, 4, 5])
Output
some string, for example "1,2,#,#,3,4,#,#,5,#,#"

Example 2

Input
deserialize(that string)
Output
[1, 2, 3, null, null, 4, 5]

Constraints

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.