iq.lab
Python starts when a code cell comes near or you run one
hardTree level by level (breadth-first)Design as coding target 40 min

Tree to text and back

Files and network messages carry text, not objects. To save a tree or send it somewhere, a program turns it into a string. Turning a structure into text is called serializing it, and turning the text back into the structure is deserializing it.

Write a class Codec with two methods:

  • serialize(root) takes the root of a binary tree (a TreeNode, or None for an empty tree) and returns a string.
  • deserialize(data) takes a string made by serialize and returns the root of a tree with the same shape and the same value at every position, built from new TreeNode objects. For an empty tree it returns None.

You choose the text format. The one rule is that deserialize(serialize(root)) rebuilds the tree. The string must carry everything: the tests serialize with one Codec and deserialize with another, so nothing may be kept outside the string. Values are integers, can be negative, and can repeat.

Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing. The output is the tree that deserialize rebuilds.

Example 1
Inputroot = [4, 2, 6, None, 3]Output[4, 2, 6, None, 3]

The rebuilt tree matches. One possible text is 4,2,6,N,3,N,N,N,N: the values row by row, with N for every missing child.

Example 2
Inputroot = []Output[]

An empty tree still becomes a string (for example N), and that string becomes None again.

Example 3
Inputroot = [-7, 10, -7, None, None, 10]Output[-7, 10, -7, None, None, 10]

Negative values, two-digit values and repeated values all come back in their places.

Constraints
  • 0 ≤ number of nodes ≤ 2 × 105

  • -1,000 ≤ node value ≤ 1,000, and values can repeat.

  • The tree is at most 500 levels deep.

  • serialize and deserialize run on different Codec objects: the string is the only thing passed between them.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.