Skip to content

Serialize and Deserialize Binary Tree

HardTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

serialize([1, 2, 3, null, null, 4, 5])  →  some string, for example "1,2,#,#,3,4,#,#,5,#,#"
deserialize(that string)                →  [1, 2, 3, null, null, 4, 5]

Constraints

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