Design an algorithm to serialize a binary tree into a string, and deserialize that string back into the original tree, using BFS (level-order traversal).
Serialization is the process of converting a data structure into a sequence of characters so that it can be stored or transmitted and reconstructed later.
You need to implement a Codec class (or equivalent) with two methods:
serialize(root) — Encodes a tree to a single string using BFS.deserialize(data) — Decodes the string back to a tree using BFS.Your serialization/deserialization algorithm should work correctly — the tree reconstructed from deserialize(serialize(root)) must be structurally identical to the original tree with the same node values.
There is no restriction on how your serialization format works. Any valid format is accepted as long as the round-trip produces the correct tree.
Hint: Think about how BFS visits nodes level by level. If you record each node's value (and use a sentinel for null children), you capture the full tree structure. Deserialization can then rebuild the tree by reading tokens in the same level-order sequence.
The tree is given as a level-order array where null represents a missing node. For example, [1,2,3,null,null,4,5] represents:
1
/ \
2 3
/ \
4 5
root = [1, 2, 3, null, null, 4, 5][1, 2, 3, null, null, 4, 5]root = [][]root = [1][1]The number of nodes in the tree is in the range [0, 10^4]-1000 <= Node.val <= 1000Your serialize and deserialize functions must be inverses of each otherExpected time complexity: O(n)Run your code to see results
Use Cmd+Enter to run