📘
Serialize and Deserialize Binary Tree
HardTrees
Design an algorithm to serialize a binary tree to a string and deserialize it back.
Input: level-order array (comma-separated, 'null' for missing). Output: serialized then deserialized back to level-order.
Example:
Input:
1,2,3,null,null,4,5
Output:
1 2 3 null null 4 5
Reasoning:
- The input string
1,2,3,null,null,4,5is first split into an array of node values, representing a level-order traversal of the binary tree. - A binary tree is constructed from this array, where
nullvalues indicate missing nodes:- Root node: 1
- Left child of 1: 2
- Right child of 1: 3
- Left child of 2: null
- Right child of 2: null
- Left child of 3: 4
- Right child of 3: 5
- The tree is then serialized to a string, which in this case is the same as the input string since the serialization is based on level-order traversal.
- The serialized string is then deserialized back to a binary tree, resulting in the same tree structure as before.
- The final output is obtained by performing a level-order traversal of the deserialized tree, resulting in
1 2 3 null null 4 5.
Constraints:
- 0 <= number of nodes <= 10^4
- -1000 <= Node.val <= 1000
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.