Skip to content

428. Serialize and Deserialize N-ary 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 an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary 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 3-ary tree

img

as [1 [3[5 6] 2 4]]. Note that this is just an example, you do not necessarily need to follow this format.

Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.

img

For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

You do not necessarily need to follow the above-suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.

Example 1:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

Example 2:

Input: root = [1,null,3,2,4,null,5,6]
Output: [1,null,3,2,4,null,5,6]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • 0 <= Node.val <= 104
  • The height of the n-ary tree is less than or equal to 1000
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.

Solution:

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Codec {
    // Encodes a tree to a single string.
    public String serialize(Node root) {
        if (root == null){
            return "null";
        }

        String result = root.val + "," + root.children.size();
        for (Node child : root.children){
            result = result + "," + serialize(child);
        }

        return result;
    }

    // Decodes your encoded data to tree.
    public Node deserialize(String data) {
        if (data.equals("null")){
            return null;
        }

        Queue<String> queue = new ArrayDeque<>(Arrays.asList(data.split(",")));
        return helper(queue);
    }

    private Node helper(Queue<String> queue){
        String cur = queue.poll();

        if (cur.equals("null")){
            return null;
        }

        Node root = new Node(Integer.valueOf(cur));
        int childrenCount = Integer.valueOf(queue.poll());
        root.children = new ArrayList<>();

        for (int i = 0; i < childrenCount; i++){
            root.children.add(helper(queue));
        }

        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Codec {

    // Encodes an N-ary tree to a single string using commas.
    public String serialize(Node root) {
        if (root == null) {
            return "null";
        }

        // 使用逗号拼接节点值和子节点数量
        String result = root.val + "," + root.children.size() + ",";
        for (Node child : root.children) {
            result += serialize(child);  // 递归地序列化每个子节点
        }

        return result;
    }

    // Decodes your encoded data to tree using commas.
    public Node deserialize(String data) {
        if (data.equals("null")) {
            return null;
        }

        Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
        return deserializeHelper(queue);
    }

    private Node deserializeHelper(Queue<String> queue) {
        String value = queue.poll();
        if (value.equals("null")) {
            return null;
        }

        // 创建节点并获取其子节点数量
        Node root = new Node(Integer.parseInt(value));
        int childrenCount = Integer.parseInt(queue.poll());
        root.children = new ArrayList<>();

        // 递归地反序列化每个子节点
        for (int i = 0; i < childrenCount; i++) {
            root.children.add(deserializeHelper(queue));
        }

        return root;
    }
}
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
        children = new ArrayList<>();
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
}

public class Codec {

    // Encodes an N-ary tree to a single string using commas.
    public String serialize(Node root) {
        if (root == null) {
            return "null";
        }

        // 记录当前节点的值
        StringBuilder sb = new StringBuilder();
        sb.append(root.val).append(",");

        // 递归序列化子节点
        for (Node child : root.children) {
            sb.append(serialize(child));
        }

        // 子节点结束标志
        sb.append("null,");

        return sb.toString();
    }

    // Decodes your encoded data to tree using commas.
    public Node deserialize(String data) {
        if (data.equals("null")) {
            return null;
        }

        Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
        return deserializeHelper(queue);
    }

    private Node deserializeHelper(Queue<String> queue) {
        String value = queue.poll();
        if (value.equals("null")) {
            return null;
        }

        // 创建当前节点
        Node root = new Node(Integer.parseInt(value));

        // 递归反序列化子节点,直到遇到 "null" 表示子节点结束
        while (!queue.isEmpty() && !queue.peek().equals("null")) {
            root.children.add(deserializeHelper(queue));
        }

        // 移除 "null" 标记
        queue.poll();

        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));