-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_428.java
More file actions
59 lines (51 loc) · 1.62 KB
/
Copy pathP_428.java
File metadata and controls
59 lines (51 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package leetcode.hard;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class P_428 {
static class Node {
public int val;
public List<Node> children;
Node(int _val) {
val = _val;
}
}
static class Codec {
// Encodes a tree to a single string.
public String serialize(Node root) {
final StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
public void serialize(Node root, StringBuilder sb) {
if (root == null) {
return;
}
sb.append(root.val + ",");
sb.append(root.children.size() + ",");
for (Node child : root.children) {
serialize(child, sb);
}
}
// Decodes your encoded data to tree.
public Node deserialize(String data) {
if (data.isEmpty()) {
return null;
}
return deserialize(new LinkedList<>(Arrays.asList(data.split(","))));
}
public Node deserialize(Deque<String> q) {
final String curr = q.removeFirst();
final String currSize = q.removeFirst();
final Node root = new Node(Integer.parseInt(curr));
final List<Node> children = new ArrayList<>();
for (int i = 0; i < Integer.parseInt(currSize); i++) {
children.add(deserialize(q));
}
root.children = children;
return root;
}
}
}