N-Ary Tree BFS Codec
Problem statement
Implement both directions of a codec for ordered N-ary trees with signed integer node values. Process each row of operations in order and return one result per row.
["SERIALIZE", tree]converts canonical tree text into the breadth-first wire format below.["DESERIALIZE", data]converts valid wire data into canonical tree text.
Canonical tree text
An empty tree is the empty string. A leaf is its decimal value. A non-leaf is its value followed by its children in parentheses, separated by commas. Child order is significant. For example, 1(3(5,6),2,4) has root 1 with children 3, 2, and 4.
Breadth-first wire format
An empty tree is again the empty string. A nonempty encoding begins with the root value. Later levels are separated by |. Within a later level, list each parent's child values from left to right and terminate that parent's child list with #. Parents are processed in the previous level's left-to-right order. Omit a final level that would contain only # markers.
For example, 1(3(5,6),2,4) serializes as 1|3,2,4,#|5,6,#,#,#. In the last segment, the first # closes node 3's children, and the remaining markers record that nodes 2 and 4 have no children.
Function
transformNaryBfsCodec(operations: String[][]) → String[]Examples
Example 1
operations = [["SERIALIZE","1(3(5,6),2,4)"],["DESERIALIZE","7|8,9,10,#|#,11,#,#"]]return = ["1|3,2,4,#|5,6,#,#,#","7(8,9(11),10)"]The first operation writes the tree level by level and uses # to close each parent's child list. In the second operation, node 9 is the only child on its level that receives a child.
Example 2
operations = [["SERIALIZE","42"],["DESERIALIZE","-1|2,3,#"]]return = ["42","-1(2,3)"]A single node needs no later level. The second wire string gives the root two leaf children.
Constraints
1 <= operations.length <= 200.- Every operation has exactly two strings and uses
SERIALIZEorDESERIALIZE. - Every supplied tree text and wire string is valid under the stated grammar.
- Each tree contains at most
5000nodes. - Every node value is a signed 32-bit integer.
- The total number of nodes across all operations is at most
20000.