# 297 Serialize and Deserialize Binary Tree

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.

For example, you may serialize the following tree

```
    1
   / \
  2   3
     / \
    4   5
```

as

`"[1,2,3,null,null,4,5]"`

You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself

**The Idea:**

* The use of `ostringstream` and `istringstream` allows us to cleanly delimit serialized words.
* Serialization is pretty simply. We just continue to append to referenced string.
* Deserialization feeds in a referenced istream object which ensures that it will be read in linearly. The key in understand how it works is that we first build a stack of `TreeNode`'s in a pre-order fashion before connecting the tree together.

![](/files/-LoJJ-_9TAhSw1TrrcRd)

```cpp
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream os;
        serialize(root, os);
        return os.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream is(data);
        return deserialize(is);
    }

private:

    void serialize(TreeNode* root, ostringstream &os) {
        if (root) {
            os << root->val << " ";
            serialize(root->left, os);
            serialize(root->right, os);
        }
        else os << "null ";
    }


    TreeNode* deserialize(istringstream &is) {
        string cur_str;
        is >> cur_str;
        if (cur_str == "null") return nullptr;

        TreeNode *temp = new TreeNode(stoi(cur_str));
        temp->left = deserialize(is);
        temp->right = deserialize(is);

        return temp;
    }
};
```

**Python**

```python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """

        pre_order = []
        def dfs(root):
            if (root):
                pre_order.append(str(root.val))
                dfs(root.left)
                dfs(root.right)
            else:
                pre_order.append('#')

        dfs(root)
        return ','.join(pre_order)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """

        data = data.split(',')
        global_iter = [0]
        def dfs(i):
            if data[i[0]] == '#':
                return None
            else:
                next_root = TreeNode(int(data[i[0]]))
                i[0] += 1
                next_root.left = dfs(i)
                i[0] += 1
                next_root.right = dfs(i)
                return next_root
        return dfs(global_iter)



# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/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.
