Save a Tree as Text and Load It Back
Implement cloneViaText
Design a way to turn a binary tree into text and back. In this exercise your solution must contain both halves — a serialize step that converts the tree to a string, and a deserialize step that builds a brand-new tree from that string — and the function returns the tree obtained after the round trip. You may choose any text format you like, as long as it records the values and the exact shape of the tree, so that the rebuilt tree equals the original.
A level-order text is easy to read but spends a "null" on every missing child slot. A pre-order text with "#" markers can be read back with a simple recursion that mirrors the tree itself.
Example 1:
Input: root = [30,12,45,8,20,null,50]
Output: [30,12,45,8,20,null,50]
Example 2:
Input: root = [7,null,7]
Output: [7,null,7]
Example 3:
Input: root = []
Output: []
+ 11 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100; −1000 ≤ node.val ≤ 1000; values may repeat - ●
The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child - ●
Inside your solution, write BOTH a serialize step (tree → text) and a deserialize step (text → a brand-new tree). You choose the text format — the only requirement is that it stores the values and the exact shape, and that it uses characters your deserializer can split on (digits, "-", ",", "#" or "null") - ●
Return the tree obtained by deserializing the text of the given tree. The returned tree must be equal to the given one in shape and values; it is checked as a level-order list
root =