Meta uses tree-shaped data in several internal systems, and a common task is converting a binary tree into a transportable string and reconstructing it later. Implement serialization and deserialization for a binary tree so that the rebuilt tree is structurally identical to the original.
Implement a function serialize_deserialize(root) that:
root, the root node of a binary tree represented as nested dictionaries with keys val, left, and right, or nullserialized: a string encoding of the treedeserialized: the reconstructed tree in the same nested dictionary formatUse level-order traversal. Represent missing children with the marker #, and separate tokens with commas.
Example 1
Input:
root = {"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":{"val":4,"left":null,"right":null},"right":{"val":5,"left":null,"right":null}}}
Output:
{"serialized":"1,2,3,#,#,4,5,#,#,#,#","deserialized":same tree}
Explanation: The string preserves both values and null positions, so the original structure can be rebuilt exactly.
Example 2
Input:
root = null
Output:
{"serialized":"#","deserialized":null}
Explanation: An empty tree is encoded as a single null marker.
[0, 10^4]-1000 <= node.val <= 1000