A tree has to be stored in a text file and read back later. Write two functions:
serialize(root)turns a binary tree into a string (any format you like).deserialize(data)turns such a string back into a tree with exactly the same shape and values.
The tests check the round trip, tree_to_list(deserialize(serialize(root))) must equal tree_to_list(root), and that serialize really returns a str (returning the tree itself does not count). An empty tree must survive the round trip too, and values may be negative.
Examples
8
/ \
-3 6
/
4
Input: root = build_tree([8, -3, 6, 4])
Output: tree_to_list(deserialize(serialize(root))) == [8, -3, 6, 4]
Input: root = build_tree([])
Output: tree_to_list(deserialize(serialize(root))) == []
Constraints
0 <= number of nodes <= 1000-1000 <= node.val <= 1000serializemust return astr
Goals
- Design a text encoding that records missing children explicitly
- Consume an encoded stream with a recursive parser that rebuilds the same shape