Hard · Trees

Serialize and deserialize

Given the root of a binary tree, encode the tree as a string and decode that string back into a tree. Return both the string and the rebuilt tree, which must have exactly the same shape and values as the original. The reference writes the tree in level order, with # for every missing child and commas between tokens; an empty tree becomes the empty string.

Examples

Example 1

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

Output: "1,2,3,#,#,4,5,#,#,#,#"

Example 2

[1,2,3]

Output: "1,2,3,#,#,#,#"

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Trees problems