Serialize and Deserialize a Binary Tree
Problem statement
Implement both directions of a binary-tree codec. Encode root and independently decode the supplied data; they need not describe the same tree.
For this exercise, assume preorder serialization: a node emits its signed decimal value, then its left subtree, then its right subtree. A null pointer emits #. Separate tokens with one comma and use no spaces or trailing comma.
Return two strings in order: the exact preorder encoding of root, and the decoded data tree represented as compact level-order JSON. Keep interior null positions and remove trailing nulls; represent an empty decoded tree as []. The supplied data is a valid canonical preorder encoding.
Function
binaryTreeCodec(root: TreeNode, data: String) → String[]Examples
Example 1
root = [1,2,3,null,null,4,5]data = "8,#,9,#,#"return = ["1,2,#,#,3,4,#,#,5,#,#","[8,null,9]"]Encode the supplied tree, then decode an unrelated right-child tree independently.
Example 2
root = []data = "#"return = ["#","[]"]A null tree is # in preorder and [] in trimmed level order.
Example 3
root = [-7,null,3,-1]data = "0,-2,#,#,0,#,#"return = ["-7,#,3,-1,#,#,#","[0,-2,0]"]Negative values, missing children and duplicate decoded values preserve their positions.
Constraints
- For this exercise, assume each input tree has from
0through500nodes, and values satisfy-10^6 <= value <= 10^6. - Decimal tokens have no leading zeros or plus sign; zero is
0. - The trees are finite, acyclic binary trees. Decoding must preserve every value and left/right link.