Serialize and Deserialize an N-Ary Tree
Problem statement
Implement a codec for finite rooted ordered N-ary trees with integer values. Process each operation independently and return one result per operation.
- For
serialize, the payload is a canonical tree description: a node isvalue[child1,child2,...], a leaf isvalue[], and an empty tree is#. Return a preorder encoding in which every non-null node contributes its value followed by its child count, with tokens separated by one space. The empty tree encodes as#. - For
deserialize, the payload is a preorder child-count encoding produced by that rule. Rebuild the tree and return its canonical tree description.
Child order must be preserved exactly.
Function
processNaryCodec(operations: String[], payloads: String[]) → String[]Examples
Example 1
operations = ["serialize","deserialize"]payloads = ["1[2[],3[4[]]]","1 2 2 0 3 1 4 0"]return = ["1 2 2 0 3 1 4 0","1[2[],3[4[]]]"]The first operation encodes the ordered tree in preorder. The second reconstructs the same tree and emits its canonical description.
Example 2
operations = ["serialize","deserialize"]payloads = ["#","-5 0"]return = ["#","-5[]"]The null tree has the single-token encoding #, while a leaf stores its value and a zero child count.
Constraints
1 <= operations.length == payloads.length <= 100- Every operation is
serializeordeserialize, and each payload is valid for its operation. - Across all operations there are at most
10000nodes and at most100000payload characters. - Node values are signed 32-bit integers.