Blind 75 · Trees

Serialize and Deserialize Binary Tree

Hard

Watch the walkthrough (6:03)

Problem

Design a way to turn a binary tree into a string, and that string back into the same tree.
serialize takes the root of a tree, and returns a string.
deserialize takes that string, and returns the root of a tree with the same shape and the same values.
How the string is written is up to you.

Examples

Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Explanation: deserialize, on a second Codec, given the string serialize returned, gives back this tree. What the string says is not checked.

Example 2:
Input: root = []
Output: []
Explanation: the empty tree has to come back empty.

Constraints

0 <= number of nodes <= 10^4
-1000 <= Node.val <= 1000

Prerequisites

Serialization — turning a structure into a flat sequence and back, and choosing a format that survives ambiguity.

How to think about it

1. Preorder With a Mark for Every Missing Child Optimal

Intuition

Values alone are not enough: another tree can list the same values in the same order. So serialize writes the tree in preorder, a node's value before its left subtree and its right, with N for every missing child and a comma between values. Every N says where a branch ends, so deserialize, reading the values back in the same order, always knows which side the next value belongs to: after a node's two N's it is finished, and the next value goes to the side still open.

Algorithm

1. serialize: write(node) appends N for a missing child, else the node's value, then write(left), then write(right); join the values with commas.
2. deserialize: split the string at the commas and hand the values over one at a time.
3. build() takes the next value: N is a missing child (return null); otherwise make a node with the value, build its left subtree, then its right, and return it.

Time & Space

Time O(n): each method visits every node and every missing child once. Space O(n): the string holds every value and every N, and the calls go as deep as the tree is tall.