AlgoFrames

Serialize a tree to a string

Warm-up · Write code · about 10 min

Write serialize(root), which turns a binary tree into a string. Walk the tree in pre-order: write a node's value, then its left subtree, then its right subtree. Write # for every missing child and join the tokens with commas, with no spaces.

The tree 1 → (2, 3) gives "1,2,#,#,3,#,#". An empty tree gives "#".

Example 1

Input:

[[1,2,3,null,4]]

Output:

1,2,#,4,#,#,3,#,#

2 has no left child, so a # comes right after 2.

Example 2

Input:

[[]]

Output:

#

An empty tree is one # token.

Constraints

  • 0 ≤ number of nodes ≤ 2,000
  • -100,000 ≤ node value ≤ 100,000

Learn the idea first: Serialization and construction, a visual lesson.

More Serialization and construction problems