Skip to content
Onsite

Serialize and Deserialize Binary Tree

HardP2Coding

Design an algorithm to turn a binary tree into a string and back. Implement the Codec class:

  • serialize(root) returns the string encoding of the tree.
  • deserialize(data) rebuilds the tree from a string produced by serialize and returns its root.

Since the tests check the strings, use this exact format: a preorder traversal (node, then left subtree, then right subtree) with values joined by ,, writing # for every missing child. For example the tree [1,2,3,null,null,4,5] is "1,2,#,#,3,4,#,#,5,#,#", and an empty tree is "#".

Example 1

Input
["Codec","serialize","deserialize"] [[],[[1,2,3,null,null,4,5]],["1,2,#,#,3,4,#,#,5,#,#"]]
Output
[null,"1,2,#,#,3,4,#,#,5,#,#",[1,2,3,null,null,4,5]]

Example 2

Input
["Codec","serialize"] [[],[[]]]
Output
[null,"#"]

Constraints

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

Hints

Run checks the 2 visible tests, Submit all 7.