Loading...
Loading...
-1000 <= Node.val <= 1000 0 <= Number of nodes <= 1000 The tree depth will not exceed 1000 Node values are integers
Serialization is the process of converting a data structure into a sequence of bits (or a string) so that it can be stored or transmitted and reconstructed later. Deserialization is the reverse process — reconstructing the original data structure from the serialized representation.
Your task is to implement two functions:
serialize(root) — converts a binary tree into a string representationdeserialize(data) — reconstructs the binary tree from that stringThere is no restriction on how your serialization/deserialization algorithm should work. The only guarantee is that deserialize(serialize(root)) must return a tree that is structurally identical with the same node values as the original.
serialize(root)
root — the root node of a binary tree (or null for an empty tree)deserialize(data)
data — a string produced by your serialize functionFor testing purposes, trees are provided in level-order (BFS) array format, where null represents a missing node (e.g., [1,2,3,null,null,4,5]).
Input tree (level-order): [1, 2, 3, null, null, 4, 5]
1
/ \
2 3
/ \
4 5
serialize → "1,2,3,null,null,4,5" (or any valid encoding)
deserialize("1,2,3,null,null,4,5") → reconstructed tree [1,2,3,null,null,4,5]
Explanation: The tree is encoded into a string. After deserialization, we recover the exact same tree structure and values.
Input tree (level-order): [1, 2]
1
/
2
serialize → "1,2,null,null,null"
deserialize → reconstructed tree [1,2]
Explanation: Missing children are encoded as null to preserve structure.
Input tree: [] (empty tree / null root)
serialize(null) → ""
deserialize("") → null
Explanation: An empty tree serializes to an empty string and deserializes back to null.
null children explicitly. This naturally produces a readable, compact format."#" or "null" for missing nodes. Deserialization uses a pointer/index into the token list.