Skip to content
BASA DSA

Serialize And Deserialize Binary Tree

HardTrees

Implement serialize(root) producing a string and deserialize(data) reconstructing a binary tree with identical structure and values. Use any complete unambiguous format. The judge tests round trips, including empty trees.

Example 1

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: 1, node 1: 2, node 2: 3, node 3: 4. Edges: node 0 (1) — node 1 (2) left child; node 0 (1) — node 2 (3) right child; node 1 (2) — node 3 (4) right child.1234
Argument 1 tree: level-order input; omitted children are null.

Input
root = [1,2,3,null,4]
Output
[1,2,3,null,4]

Explanation

Preserve the null left child below 2 so 4 returns as its right child.

Example 2

Argument 1 tree: empty tree (null root).
Input
root = []
Output
null

Explanation

The empty tree must not become a leaf during round-trip.

Example 3

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: -2, node 1: 5. Edges: node 0 (-2) — node 1 (5) right child.-25
Argument 1 tree: level-order input; omitted children are null.

Input
root = [-2,null,5]
Output
[-2,null,5]

Explanation

Preserve the negative root, missing left child and right child 5.

Constraints

  • 0 <= number of nodes <= 10000
  • Values are signed 32-bit integers
  • deserialize receives a serialization produced by your encoder

Function contractserializeArguments: tree
Loading draft…
SolutionRuns on your device
Loading draft…