serialize-and-deserialize-binary-tree.sh — zsh
binary-treedepth-first-searchbreadth-first-searchdesign

Serialization is the process of converting a binary tree into a string so that it can be stored or transmitted and later reconstructed into the exact same tree structure and node values.

Implement serialize(root) and deserialize(data) and return deserialize(serialize(root)) from serialize_and_deserialize.

Input / output

  • Input: root: TreeNode (represented in level-order array form in test fixtures)
  • Output: TreeNode — the reconstructed binary tree

Constraints

  • The number of nodes in the tree is in the range [0, 10^4]
  • -1000 <= Node.val <= 1000

Follow-up

How would you adapt your format if the tree were guaranteed to be a Binary Search Tree (BST) so you wouldn't need to store null markers?

Examples
Example 1
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2: empty tree
Input: root = []
Output: []
Example 3: right-skewed chain
Input: root = [1,null,2,null,3]
Output: [1,null,2,null,3]