# 297. Serialize and Deserialize Binary Tree!

```java
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serializeHelp(root, sb);
        return sb.toString();
    }
    
    private void serializeHelp(TreeNode node, StringBuilder sb){
        // use preorder dfs, 
        // so that the root node is created before the childern during deserialization
        // "N" for null, " " for split
        if(node == null){
            sb.append("N ");
            return;
        }
        sb.append(node.val+" ");
        serializeHelp(node.left, sb);
        serializeHelp(node.right, sb);
    } 

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        List<String> strList = Arrays.asList(data.split(" "));
        Queue<String> list = new LinkedList<>(strList);
        return deserializeHelp(list);
    }
    
    private TreeNode deserializeHelp(Queue<String> list){
        // dfs and bulid the tree same order as serialization
        String str = list.poll();
        if(str.equals("N")) return null;
        
        TreeNode node = new TreeNode(Integer.parseInt(str));
        node.left=deserializeHelp(list);
        node.right=deserializeHelp(list);
        return node;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.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://ucan.gitbook.io/notes/algorithm/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.
