Serialize and Deserialize Binary Tree

HardTrees

Write two functions. serialize(root) turns a binary tree into a string, in any format you like. deserialize(data) takes that string and rebuilds the same tree, returning its root.

The string must carry the whole tree: the tests build a tree, call serialize, take apart the original tree, then call deserialize on your string and compare what comes back with the tree they started from. Values can be negative and can have several digits.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1. The output is the tree deserialize returned, written the same way.

Examples

Example 1
Input:  root = [7, -3, 12, null, 4, 10]
Output: [7, -3, 12, null, 4, 10]

Whatever string serialize makes, deserialize must turn it back into this exact tree.

Example 2
Input:  root = [100, null, -25, 8]
Output: [100, null, -25, 8]

The root has only a right child, so the string must record the missing left one.

Constraints

  • The tree has 0 to 10⁴ nodes.
  • -1000 ≤ node.val ≤ 1000

Stuck?

Hint 1

A list of the values alone loses the shape. Write a marker for every missing child as well, and the shape can be read back.

Hint 2

Write a preorder walk with a marker such as # for null and commas between the tokens. To rebuild, split on the commas and read the tokens in the same order with one recursive function; splitting keeps negative and many-digit values whole.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur