Serialize and Deserialize Binary Tree
Hard · Trees · Tree · DFS · BFS · Design · String
Problem
Write a Codec class that turns a binary tree into a string and back:
- serialize(root) — return a string
- deserialize(data) — rebuild the identical tree from that string
The format is entirely your choice; it only has to round-trip. Values may be negative, and the tree may be empty.
The tests build a tree, serialize it, deserialize the result, and compare the tree that comes back.
Examples
Input: root = [1,2,3,None,None,4,5] Output: the same tree after a round trip
Any encoding works as long as deserialize(serialize(t)) reproduces t.
Constraints
- 0 <= number of nodes <= 10^4
- -1000 <= Node.val <= 1000
- serialize must return a string
Approaches
- Level-order with null markers — time O(n) both, space O(n)
Related problems
Start free on Cariara · Coding problems · System design studio