Editor

Save and Restore a Tree

#172 · Trees · Expert · 195 XP · about 35 min

To store a binary tree in a file or send it over a network, you turn it into text, and later you rebuild the tree from that text. Write a class TreeCodec with two methods:

  • serialize(self, root) returns a string that describes the whole tree.
  • deserialize(self, text) takes such a string and returns the root of a tree with the same shape and the same values (None for an empty tree).

You design the text format: the tests check only that it is a string, that equal trees give equal text, and that it turns back into an identical tree, even when a new TreeCodec reads it. Write both directions yourself, without calling the provided build and to_list, which are there for the tests.

Examples

codec = TreeCodec()
text = codec.serialize(build([7, 3, 9, None, 4, 8]))
isinstance(text, str)  # returns True
to_list(codec.deserialize(text))  # returns [7, 3, 9, None, 4, 8]
to_list(codec.deserialize(codec.serialize(build([]))))  # returns []

The tree build([7, 3, 9, None, 4, 8]) survives the round trip unchanged, and so does the empty tree.

Constraints

  • 0 to 2,000 nodes. Values are integers from -1,000 to 1,000, so they can be negative or have several digits.
  • Values can repeat.

Note

  • Each node is a Node with a value val and two children, left and right.
  • Two trees that hold the same values in different shapes must give different text.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.