CodeSpeek

Serialize And Deserialize Binary Tree

Hard · Trees

Design a codec that turns a binary tree into a string and turns that string back into the same tree. The encoding is up to you — the only requirement is that deserialize(serialize(root)) gives back a tree identical in shape and values. Your class must define both serialize(self, root) and deserialize(self, data).

Examples

Input:  root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Why:    Whatever string you produce, deserialising it must rebuild the same tree.
Input:  root = []
Output: []
Why:    An empty tree must survive the round trip too.

Constraints

Up to 10^4 nodes; node values fit in a 32-bit signed integer and may be negative.

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Serialize And Deserialize Binary Tree

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Serialize And Deserialize Binary Tree. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.