Serialize and Deserialize Binary Tree
HardTrees
Design a Codec class that turns a binary tree into a string and back:
serialize(root)takes the root of a binary tree and returns a string that encodes it.deserialize(data)takes a string produced byserializeand returns the root of the tree it encodes.
The format is entirely up to you. The only requirement is that the round trip is exact: deserialize(serialize(root)) must rebuild a tree with the same shape and the same values as root. The grader never inspects the string itself; it calls serialize, then passes the string to deserialize on a fresh Codec instance and compares the rebuilt tree with the original. So the string must carry all the information: do not keep the tree in instance, class, or global variables.
Values can be negative and can repeat, and the tree can be empty.
In the examples, root is written in level order (null marks a missing child), and the output is the tree that your deserialize must return.
Example 1
- Input:
- root = [4,-2,9,null,3,null,null,1]
- Output:
- [4,-2,9,null,3,null,null,1]
- Explanation
- One valid encoding is the preorder string
"4,-2,#,3,1,#,#,#,9,#,#", where#marks a missing child. Deserializing that string rebuilds exactly this tree, including the negative value and the missing children.
Example 2
- Input:
- root = []
- Output:
- []
- Explanation
- An empty tree must survive the round trip too:
serializereturns some string (for example"#") thatdeserializeturns back intoNone.
Example 3
- Input:
- root = [7,7,null,7]
- Output:
- [7,7,null,7]
- Explanation
- Repeated values are fine as long as the encoding records where each node sits; a format that stored only the values would lose the shape.
Constraints
- The number of nodes is in the range
[0, 10^4] -1000 <= Node.val <= 1000- The tree height is at most
500