Instructions
Write a class Codec with two methods:
serialize(root)gets the root of a binary tree and returns a string that describes the whole tree;deserialize(data)gets such a string and builds the same tree again, then returns its root.
You choose the text format. Any format is fine, as long as deserialize can rebuild the tree exactly from the text that serialize made.
How your class is checked
For each test, the judge creates one new Codec object and calls serialize on the tree. Then it creates a second, separate Codec object and calls deserialize with that string. The tree you return must have the same shape and the same values as the tree that was given.
serializemust return a string. Any other type fails the test.- The two objects are different, so you cannot keep the tree inside the object. All the information must be in the string.
- The tree can be empty (
rootisnull/None). Thendeserializemust returnnull/None. - Values can be negative, can have more than one digit, and can repeat.
How the input is shown
The tree is written in level order: the values row by row, from left to right, with null where a child is missing. For example, [1, 2, 3, null, 4] is the root 1 with children 2 and 3, and 4 is the right child of 2. The expected output is the same tree, because a correct round trip gives back what it was given.
Hint
Visit the nodes in pre-order (node, then left, then right) and write a marker such as # for every missing child. With the markers, the order of the values alone is enough to rebuild the tree. Put a separator such as a comma between items.
Examples
Example 1
- Input:
- [7,-3,12,null,null,40,-15]
- Output:
- [7,-3,12,null,null,40,-15]
One possible pre-order text is "7,-3,#,#,12,40,#,#,-15,#,#". Reading it back from the left rebuilds 7, then its left child -3 (with no children), then its right child 12 with children 40 and -15.
Example 2
- Input:
- []
- Output:
- []
The tree is empty. serialize must still return a string (for example "#" or ""), and deserialize must turn it back into an empty tree.
Example 3
- Input:
- [5,5,null,5,null,5]
- Output:
- [5,5,null,5,null,5]
Four nodes with the same value, each one the left child of the one above. The values alone cannot tell the shape, so the text must also record where children are missing.
Constraints
- The tree has between
0and40nodes. -99 <= Node.val <= 99
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [7,-3,12,null,null,40,-15]
- Expected:
- [7,-3,12,null,null,40,-15]
- Input:
- []
- Expected:
- []
- Input:
- [5,5,null,5,null,5]
- Expected:
- [5,5,null,5,null,5]
Run checks your code against the 3 examples. Submit checks it against all 113 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.