列表

详情


428. 序列化和反序列化 N 叉树

序列化是指将一个数据结构转化为位序列的过程,因此可以将其存储在文件中或内存缓冲区中,以便稍后在相同或不同的计算机环境中恢复结构。

设计一个序列化和反序列化 N 叉树的算法。一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。序列化 / 反序列化算法的算法实现没有限制。你只需要保证 N 叉树可以被序列化为一个字符串并且该字符串可以被反序列化成原树结构即可。

例如,你需要序列化下面的 3-叉 树。

 

 

为 [1 [3[5 6] 2 4]]。你不需要以这种形式完成,你可以自己创造和实现不同的方法。

或者,您可以遵循 LeetCode 的层序遍历序列化格式,其中每组孩子节点由空值分隔。

例如,上面的树可以序列化为 [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]

你不一定要遵循以上建议的格式,有很多不同的格式,所以请发挥创造力,想出不同的方法来完成本题。

 

示例 1:

输入: 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]
输出: [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]

示例 2:

输入: root = [1,null,3,2,4,null,5,6]
输出: [1,null,3,2,4,null,5,6]

示例 3:

输入: root = []
输出: []

 

提示:

相似题目

二叉树的序列化与反序列化

序列化和反序列化二叉搜索树

将 N 叉树编码为二叉树

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Codec { public: // Encodes a tree to a single string. string serialize(Node* root) { } // Decodes your encoded data to tree. Node* deserialize(string data) { } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));

python3 解法, 执行用时: 76 ms, 内存消耗: 19.5 MB, 提交时间: 2023-10-21 19:52:04

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=[]):
        self.val = val
        self.children = children
"""
class Codec:

    def serialize(self, root: 'Node') -> str:
        """Encodes a tree to a single string.
        
        :type root: Node
        :rtype: str
        """
        from collections import deque
        if not root: return ""  
        queue = deque([root])
        res = []
        while queue:
            node = queue.pop()
            res.append(str(node.val))
            res.append(str(len(node.children)))
            for ch in node.children:
                queue.appendleft(ch)
        return ",".join(res)

    def deserialize(self, data: str) -> 'Node':
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: Node
        """
       #  print(data)
        from collections import deque
        if not data: return 
        data = iter(data.split(","))
        root = Node(int(next(data)), [])
        queue = deque([[root, int(next(data))]])

        while queue:
            node, num = queue.pop()
            for _ in range(num):
                tmp = int(next(data))
                tmp_num = int(next(data))
                tmp_node = Node(tmp, [])
                node.children.append(tmp_node)
                queue.appendleft([tmp_node, tmp_num])
        return root

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

python3 解法, 执行用时: 64 ms, 内存消耗: 19.5 MB, 提交时间: 2023-10-21 19:51:42

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=[]):
        self.val = val
        self.children = children
"""
class Codec:

    def serialize(self, root: 'Node') -> str:
        """Encodes a tree to a single string.
        
        :type root: Node
        :rtype: str
        """
        res = []  

        def dfs(root):
            if not root: return 
            res.append(str(root.val))
            res.append(str(len(root.children)))
            for ch in root.children:
                dfs(ch)
        
        dfs(root)
        # print(res)
        return ",".join(res)

    def deserialize(self, data: str) -> 'Node':
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: Node
        """
        if not data: return 
        data = iter(data.split(","))
        
        def dfs():
            root = Node(int(next(data)), [])
            num = int(next(data))
            for _ in range(num):
                root.children.append(dfs())
            return root
        
        return dfs()
        

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

cpp 解法, 执行用时: 40 ms, 内存消耗: 172.4 MB, 提交时间: 2023-10-21 19:51:13

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(Node* root) {
        if (root == NULL)
            return "";
        string res = to_string(root->val) + "[";
        for (auto node : root->children) {
            res += serialize(node) + ",";
        }
        if (res.back() == ',')
            res.pop_back();
        res += "]";
        return res;
    }

    // Decodes your encoded data to tree.
    Node* deserialize(string data) {
        cout << data << endl;
        string value;
        Node* head = NULL;
        stack<Node*> s;
        for (int i = 0; i < data.size(); ++i) {
            const char& c = data[i];
            if ((c >= '0' && c <= '9') || c == '+' || c == '-') {
                value += c;
            } else if (c == '[') {
                Node* node = new Node(stoi(value));
                if (head == NULL)
                    head = node;
                s.push(node);
                value.clear();
            } else if (c == ']') {
                Node* node = s.top();
                s.pop();
                if (!s.empty()) {
                    Node* prev_node = s.top();
                    prev_node->children.push_back(node);
                }
            }
        }
        return head;
    }
};

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

java 解法, 执行用时: 7 ms, 内存消耗: 44.8 MB, 提交时间: 2023-10-21 19:50:32

/*
// 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) {
        StringBuilder sb = new StringBuilder();
        if (root == null) {
            return sb.toString();
        }
        encode(root, sb);
        return sb.toString();
    }

    private void encode(Node node, StringBuilder sb) {
        if (node == null) {
            return;
        }
        sb.append(node.val);
        sb.append(" ");

        boolean hasChildren = !node.children.isEmpty();
        
        // only append "[ ]" when the node has children
        if (hasChildren) {
            sb.append("[ ");
        }
        for (int i = 0; i < node.children.size(); i++) {
            Node children = node.children.get(i);
            encode(children, sb);
            if (i == node.children.size() - 1) {
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        if (hasChildren) {
            sb.append(" ] ");
        }
    }

    // Decodes your encoded data to tree.
    public Node deserialize(String data) {
        if (data.isEmpty()) {
            return null;
        }
        String[] strings = data.split(" ");
        Stack<Node> stack = new Stack<Node>();
        Node root = null;
        Node cur = null;

        for (String s : strings) {
            if (s.equals("[")) {
                stack.push(cur);
            } else if (s.equals("]")) {
                stack.pop(); 
            } else {
                Node node = new Node(Integer.valueOf(s));
                node.children = new LinkedList<Node>();
                if (root == null) {
                    root = node;
                } else {
                    Node parent = stack.peek();
                    parent.children.add(node);
                }
                cur = node;
            }
        }

        return root;
    }
}

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

上一题