LeetCode 428. Serialize and Deserialize N-ary Tree
原题链接在这里:https://leetcode.com/problems/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
as [1 [3[5 6] 2 4]]
. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note:
N
is in the range of[1, 1000]
- Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
题解:
Serialize the tree with preorder traverse. For each node, serialize its value, then the size of its children.
Then example tree is serialized like 1,3, 3,2, 5,0, 6,0, 2,0, 4,0
When deserializing, convert the string into queue. Poll the first 2 numbers, first is the value, second is the size of children.
Construct the new Node, and for the size of its children, recursize call and add result back to its children.
Time Complexity: serialize, O(n). deserialize, O(n).
Space: O(n).
AC Java:
1 /* 2 // Definition for a Node. 3 class Node { 4 public int val; 5 public List<Node> children; 6 7 public Node() {} 8 9 public Node(int _val,List<Node> _children) { 10 val = _val; 11 children = _children; 12 } 13 }; 14 */ 15 class Codec { 16 17 // Encodes a tree to a single string. 18 public String serialize(Node root) { 19 List<String> ls = new LinkedList<String>(); 20 serial(root, ls); 21 22 return String.join(",", ls); 23 } 24 25 private void serial(Node root, List<String> ls){ 26 if(root == null){ 27 return; 28 } 29 30 ls.add(String.valueOf(root.val)); 31 ls.add(String.valueOf(root.children.size())); 32 for(Node child : root.children){ 33 serial(child, ls); 34 } 35 } 36 37 // Decodes your encoded data to tree. 38 public Node deserialize(String data) { 39 if(data == null || data.length() == 0){ 40 return null; 41 } 42 43 LinkedList<String> que = new LinkedList<String>(); 44 que.addAll(Arrays.asList(data.split(","))); 45 return deserial(que); 46 } 47 48 private Node deserial(LinkedList<String> que){ 49 int val = Integer.valueOf(que.poll()); 50 int size = Integer.valueOf(que.poll()); 51 52 Node root = new Node(val, new ArrayList<Node>()); 53 for(int i = 0; i<size; i++){ 54 root.children.add(deserial(que)); 55 } 56 57 return root; 58 } 59 } 60 61 // Your Codec object will be instantiated and called as such: 62 // Codec codec = new Codec(); 63 // codec.deserialize(codec.serialize(root));
AC Python:
1 """ 2 # Definition for a Node. 3 class Node(object): 4 def __init__(self, val=None, children=[]): 5 self.val = val 6 self.children = children 7 """ 8 9 class Codec: 10 def serialize(self, root: 'Node') -> str: 11 """Encodes a tree to a single string. 12 13 :type root: Node 14 :rtype: str 15 """ 16 ls = [] 17 self._serial(root, ls) 18 return ','.join(ls) 19 20 def _serial(self, root, ls): 21 if not root: 22 return 23 ls.append(str(root.val)) 24 ls.append(str(len(root.children))) 25 for child in root.children: 26 self._serial(child, ls) 27 28 29 def deserialize(self, data: str) -> 'Node': 30 """Decodes your encoded data to tree. 31 32 :type data: str 33 :rtype: Node 34 """ 35 if not data: 36 return None 37 que = data.split(',') 38 return self._deserial(iter(que)) 39 40 def _deserial(self, que): 41 val = int(next(que)) 42 size = int(next(que)) 43 root = Node(val) 44 root.children = [self._deserial(que) for _ in range(size)] 45 return root 46 47 48 # Your Codec object will be instantiated and called as such: 49 # codec = Codec() 50 # codec.deserialize(codec.serialize(root))
类似Serialize and Deserialize Binary Tree, Serialize and Deserialize BST.