Polski

Serialize a binary tree

Write a binary tree to a string and rebuild it – with empty subtrees, negative numbers and trees thousands of levels deep. Format design, BFS and the recursion trap.

hard · typescript · javascript · python · csharp · java · go · 40 XP

A service stores decision trees in a database as text and rebuilds them in memory after reading. We need to design a format and write two functions: serialize, turning a tree into a string, and deserialize, rebuilding from that string a tree with an identical shape and values.

Task

A node has an integer value and two children (left, right), each of which may be empty. The node class is already in the starter code.

  • serialize(root) returns a string (also for an empty tree),
  • deserialize(data) returns the root of a new tree (or an empty root for an empty tree),
  • deserialize(serialize(t)) must have exactly the same shape and values as t,
  • the format is up to you, but the string must be linear in the number of nodes (the tests check at most 24 characters per node plus a constant), and deserialization may use only the string (no global variables or object caches).
LanguageAPI
JS/TSclass TreeNode { val, left, right }, serialize(root), deserialize(data)
Pythonclass TreeNode, serialize(root), deserialize(data)
C#TreeNode { Val, Left, Right }, Codec.Serialize(root), Codec.Deserialize(data)
JavaTreeNode { val, left, right }, Codec.serialize(root), Codec.deserialize(data)
Gotype TreeNode struct { Val int; Left, Right *TreeNode }, Serialize(root), Deserialize(data)

Example

The tree written level by level as [1, 2, 3, null, null, 4, 5]:

    1
   / \
  2   3
     / \
    4   5

could be stored e.g. as "1,2,3,#,#,4,5,#,#,#,#" (BFS with # for empty children) or "1,2,#,#,3,4,#,#,5,#,#" (preorder). All that matters is that deserialize rebuilds the same tree.

Constraints

  • Up to 100,000 nodes, depth up to 3,000, values in the 32-bit int range (including negative and repeated ones).
  • The tree may be a "list" 3,000 levels deep – recursion in Python (default limit about 1,000 levels) will not do.

Expected complexity

Both operations in O(n) time and O(n) memory.

Topics: Memento