noodleProblems/
Serialize and Deserialize Binary Tree
#140

Serialize and Deserialize Binary Tree

AlgorithmhardStringTreeDepth First SearchBreadth First SearchBinary Tree

Design a codec for a binary tree: a **serialize** step that turns the tree into a single string, and a **deserialize** step that rebuilds the *exact* same tree from that string. A correct codec is a perfect round trip — deserialize(serialize(t)) must equal t.

This sandbox runs one function, so implement the whole round trip in serializeDeserialize(root): serialize root to a string of your own format, then parse that string back into a tree and return it. You may choose any string format (preorder with null markers is a common one) as long as the rebuilt tree matches the original.

The tree is given (and the result is checked) as a level-order array where null marks a missing child.

Example cases

  • classic
    in root = [1,2,3,null,null,4,5]21435
    out [1,2,3,null,null,4,5]21435
    Serialize to a string, parse it back — the rebuilt tree is identical.
  • empty
    in root = []null
    out []null
  • single
    in root = [1]1
    out [1]1

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -1000 <= Node.val <= 1000
Saved
root =
[1,2,3,null,null,4,5]