मुख्य कंटेंट तक स्किप करें
Back to ChallengesSerialize and Deserialize Binary TreeHard 45 min

Serialize and Deserialize Binary Tree

Design an algorithm to **serialize** a binary tree to a string and **deserialize** that string back to the original tree structure.

- `serialize(root)` → string

- `deserialize(data)` → TreeNode

There is no restriction on how your serialization/deserialization algorithm works, as long as a tree can be serialized to a string and this string can be deserialized to the original tree structure.

Examples

Input: root = [1,2,3,null,null,4,5]
Output: Same tree reconstructed
serialize then deserialize returns the same tree.
Input: root = []
Output: null
Empty tree.

Constraints

  • Number of nodes in [0, 10^4]
  • -1000 <= Node.val <= 1000

Complexity Analysis

Time
O(n) for both serialize and deserialize.
Space
O(n) for the output string and reconstruction queue.

Test Cases

#1 Standard tree round-trip
Input: [1,2,3,null,null,4,5]
Expected: [1,2,3,null,null,4,5]
#2 Empty tree
Input: []
Expected: []
#3 Single node
Input: [1]
Expected: [1]
#4 Left-skewed
Input: [1,2,null,3]
Expected: [1,2,null,3]
JavaScript
Output
Click "Run Code" to see output here...