[LeetCode] 428. Serialize and Deserialize N-ary Tree

N叉树的序列化和反序列化。题意跟297题几乎一样,唯一的不同是从二叉树换成了N叉树。例子,

思路跟297题很接近,BFS + recursion。

时间O(n)

空间O(n)

 1 class Codec {
 2 
 3     // Encodes a tree to a single string.
 4     public String serialize(Node root) {
 5         List<String> list = new LinkedList<>();
 6         serializeHelper(root, list);
 7         return String.join(",", list);
 8     }
 9 
10     private void serializeHelper(Node root, List<String> list) {
11         if (root == null) {
12             return;
13         } else {
14             list.add(String.valueOf(root.val));
15             list.add(String.valueOf(root.children.size()));
16             for (Node child : root.children) {
17                 serializeHelper(child, list);
18             }
19         }
20     }
21 
22     // Decodes your encoded data to tree.
23     public Node deserialize(String data) {
24         if (data.isEmpty())
25             return null;
26 
27         String[] ss = data.split(",");
28         Queue<String> queue = new LinkedList<>(Arrays.asList(ss));
29         return deserializeHelper(queue);
30     }
31 
32     private Node deserializeHelper(Queue<String> queue) {
33         Node root = new Node();
34         root.val = Integer.parseInt(queue.poll());
35         int size = Integer.parseInt(queue.poll());
36         root.children = new ArrayList<Node>(size);
37         for (int i = 0; i < size; i++) {
38             root.children.add(deserializeHelper(queue));
39         }
40         return root;
41     }
42 }
43 
44 // Your Codec object will be instantiated and called as such:
45 // Codec codec = new Codec();
46 // codec.deserialize(codec.serialize(root));

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12453316.html