Serialize and deserialize
Standard · Write code · about 15 min
A tree was written with the pre-order format: values and # markers for missing children, joined by commas. For example 1 → (2, 3) is "1,2,#,#,3,#,#".
Write deserialize(data), which rebuilds the tree and returns its root. Together with serialize from the warm-up, this is a full codec: deserialize(serialize(t)) has the same shape and values as t.
Example 1
Input:
["1,2,#,4,#,#,3,#,#"]
Output:
[1,2,3,null,4]
The output is shown in level order, with null for a missing child.
Example 2
Input:
["#"]
Output:
[]
One # is the empty tree.
Constraints
- 0 ≤ number of nodes ≤ 2,000
- -100,000 ≤ node value ≤ 100,000
- data is a valid encoding
Learn the idea first: Serialization and construction, a visual lesson.
More Serialization and construction problems
- Serialize a tree to a string Warm-up
- Count distinct encodings Standard
- Build a balanced BST from a sorted array Standard
- Trace deserialize Standard