← DiffPush

Serialize and Deserialize Binary Tree

DiffPush Tier Binary Trees · Hard O(n) · O(n)

The Blueprint Wire Format for Relay Towers

A telecom ops team must snapshot the live relay-tower tree and ship it to a DR site that rebuilds it byte-for-byte. The wire format is theirs to choose — the contract only demands that every tower, gap, and branch position survives the trip: encode the structure into one string, and later decode that string back into the identical tree.

Input: A binary tree as a level-order array (null marks a missing child).

Output: Return the preorder serialization — comma-separated node values with the literal token N for every missing child, e.g. '1,2,N,N,3,N,N'.

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5,null,6]}
Output: "1,2,4,N,N,5,N,N,3,N,6,N,N"
Preorder walks 1, its full left wing 2-4-5 with null bookends, then 3 and its right child 6.

Example 2

Input: {"tree":[1,null,2,3]}
Output: "1,N,2,3,N,N,N"
The root's missing left child is recorded as N before the right spine 2-3 is unrolled.

Solve this in your browser →

Also on LeetCode ↗