Top 150 InterviewСредний

Serialize And Deserialize Binary Tree

Detailed guide and Python implementation for the 'Serialize And Deserialize Binary Tree' problem.

Постановка задачи

Средний

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

The tree is represented as a level-order list. Implement two functions:

- serialize(root: list) -> str that converts the tree to a string.

- deserialize(data: str) -> list that converts the string back to the tree.

For testing, implement serializeDeserialize(root: list) -> list that serializes and then deserializes, returning the result.

Ограничения
  • The number of nodes in the tree is in the range [0, 10000]
  • -1000 <= Node.val <= 1000

Примеры

Example 1
Input
[1,2,3,None,None,4,5]
Output
[1,2,3,None,None,4,5]
Explanation

The tree is serialized to a string and deserialized back to the same tree structure.

Example 2
Input
[]
Output
[]
Explanation

An empty tree serialized and deserialized remains empty.

Need a Hint?
Consider using Trees-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Готовы решить?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Открыть в редакторе
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Рекомендуемые ресурсы Python

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.

Учебник по Python

Python Try/Except и обработка ошибок

Предотвратите сбой ваших скриптов Python. Узнайте, как блокировать try, кроме, наконец, и как правильно создавать пользовательские исключения.

Посмотреть ресурс
Практическое руководство

Как генерировать случайные числа в Python

Узнайте, как генерировать случайные числа в Python. Сравните randrange, randint и генерацию равномерного числа с плавающей запятой с контролем заполнения.

Посмотреть ресурс
Шпаргалка

Памятка по диспетчеру пакетов Python pip

Справочное руководство по командной строке для pip. Научитесь устанавливать, обновлять, удалять пакеты и зависимости Python, а также управлять ими.

Посмотреть ресурс
Сравнение языков

Python против JavaScript: какой язык программирования лучше?

Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.

Посмотреть ресурс