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.
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 ast,- 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).
| Language | API |
|---|---|
| JS/TS | class TreeNode { val, left, right }, serialize(root), deserialize(data) |
| Python | class TreeNode, serialize(root), deserialize(data) |
| C# | TreeNode { Val, Left, Right }, Codec.Serialize(root), Codec.Deserialize(data) |
| Java | TreeNode { val, left, right }, Codec.serialize(root), Codec.deserialize(data) |
| Go | type 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
intrange (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