> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Serialize and Deserialize BST Python Solution

> Tested Python solution for LeetCode 449 with 27 pytest cases. Generate a practice environment with lcpy.

LeetCode 449, [Medium](/catalog/medium). Topics: [String](/catalog/topics/string), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Design](/catalog/topics/design), [Binary Search Tree](/catalog/topics/binary-search-tree), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/serialize-and-deserialize-bst/description/).

Generate this problem as a practice environment: tested reference solution, 27 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 449   # by problem number
lcpy gen -s serialize_and_deserialize_bst   # by problem name
```

## Problem

Serialization is 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 search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

### Examples

```
Input: root = [2,1,3]
Output: [2,1,3]
```

```
Input: root = []
Output: []
```

### Constraints

* The number of nodes in the tree is in the range \[0, 10^4].
* 0 \<= Node.val \<= 10^4
* The input tree is guaranteed to be a binary search tree.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/serialize_and_deserialize_bst/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/serialize_and_deserialize_bst/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Codec:
    # Time: O(n) serialize, O(h) amortized per node for deserialize
    # Space: O(n)
    def __init__(self) -> None:
        pass

    def serialize(self, root: TreeNode[int] | None) -> str:
        values: list[str] = []
        stack: list[TreeNode[int]] = [root] if root is not None else []
        while stack:
            node = stack.pop()
            values.append(str(node.val))
            if node.right is not None:
                stack.append(node.right)
            if node.left is not None:
                stack.append(node.left)
        return ",".join(values)

    def deserialize(self, data: str) -> TreeNode[int] | None:
        values = [int(token) for token in data.split(",") if token]
        if not values:
            return None

        root = TreeNode(values[0])
        stack: list[TreeNode[int]] = [root]
        for value in values[1:]:
            node = TreeNode(value)
            if value < stack[-1].val:
                stack[-1].left = node
            else:
                parent = stack[-1]
                while stack and stack[-1].val < value:
                    parent = stack.pop()
                parent.right = node
            stack.append(node)
        return root
```

## Complexity

| Time | Space |
| - | - |
| O(n) serialize, O(h) amortized per node for deserialize | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.