CodingNodes / Trees / Serialize and Deserialize Binary Tree System design Space play · ←→ step · R restart

Problem

Design a Codec that turns a binary tree into a string and back.

  • serialize(root) returns a string that describes the tree.
  • deserialize(data) takes a string made by serialize and rebuilds the same tree.

The format is up to you, as long as the round trip returns an identical tree. The tree is given in level order, with null for a missing child. In the examples, the string passed to deserialize is the one this solution produces.

Constraints

  • 0 ≤ number of nodes ≤ 10000
  • -1000 ≤ Node.val ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each node is written once and read once, and each empty child adds one marker, so the work is about 2n tokens.

Space: The token list holds 2n + 1 items, and the recursion is as deep as the tree is tall (up to n for a chain).

Walk the tree in preorder (node, then left, then right) and write a "#" for every empty child. Those markers pin down the shape, so the list of tokens is enough on its own. To rebuild, read the tokens in the same order: a number makes a node whose left and right come from the next reads, and "#" means null.