# x 297. Serialize and Deserialize Binary Tree

{% embed url="<https://leetcode.com/problems/serialize-and-deserialize-binary-tree/>" %}

[LeetCode - The World's Leading Online Programming Learning Platform](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solutions/3902807/clean-preorder-dfs-leetcode-bfs-simplest-possible-bonus-solutions-beats-100-typescript/)

> time: O(n)

> space: O(n)

```jsx
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
let arr = [];
var serialize = function (root, idx = 0) {
    arr = [];
    serializeHelper(root);
    return arr.join(',');;
};

function serializeHelper(root, idx = 0) {
    if (root === null) {
        arr.push('null');
        return;
    }

    arr.push(root.val);
    const left = serializeHelper(root.left);
    const right = serializeHelper(root.right);
    return arr;
}

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
 let idx;
var deserialize = function (data) {
    idx = 0;
    arr = data.split(',')
    return deserializeHelper(arr);
};

function deserializeHelper(arr) {
    if (idx >= arr.length) return null;

    if (arr[idx] === 'null') {
        idx++;
        return null;
    }

    const root = new TreeNode(Number(arr[idx]));
    idx++;
    root.left = deserializeHelper(arr);
    root.right = deserializeHelper(arr);

    return root;
}

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/x-297.-serialize-and-deserialize-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
