> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/428.-serialize-and-deserialize-n-ary-tree.md).

# 428. Serialize and Deserialize N-ary Tree

序列化N叉树，每个结点N不一定一样。和序列化二叉树一样可以DFS或BFS做。区别在于N未知，需要额外存下当前结点children的size。

题目和代码参考了[这](https://www.cnblogs.com/grandyang/p/9945453.html)。

```cpp
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(Node* root) {
        string res;
        serialize(node, res);
        return res;   
    }

    void serialize(Node *node, string &res) {
        if (node == nullptr) {
            res += '#';
            return;
        }
        res += to_string(node->val) + " " + to_string(node->children.size()) + " ";
        for (const auto child : node->children) {
            serialize(child, res);
        }
    }

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

    Node* deserialize(istringsteam &iss) {
        string val;
        iss >> val;
        if (val == '#') return nullptr;
        string size;
        iss >> size;
        Node *node = new Node(stoi(val), {});
        for (int i = 0; i < stoi(size); ++i) {
            node->children.push_back(deserialize(iss));
        }
        return node;
    }

};

```
