|
| 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 | + StringBuilder sb; |
| 19 | + public String serialize(Node root) { |
| 20 | + if (root == null) { |
| 21 | + return ""; |
| 22 | + } |
| 23 | + |
| 24 | + sb = new StringBuilder(); |
| 25 | + serializeHelper(root); |
| 26 | + |
| 27 | + return sb.toString().substring(0, sb.length() - 1); |
| 28 | + } |
| 29 | + |
| 30 | + private void serializeHelper(Node root) { |
| 31 | + if (root == null) { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + sb.append(root.val).append(",").append(root.children.size()).append(","); |
| 36 | + for (Node child : root.children) { |
| 37 | + serializeHelper(child); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Decodes your encoded data to tree. |
| 42 | + public Node deserialize(String data) { |
| 43 | + if (data == null || data.length() == 0) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + Queue<String> queue = new LinkedList<>(); |
| 48 | + queue.addAll(Arrays.asList(data.split(","))); |
| 49 | + |
| 50 | + return deserializeHelper(queue); |
| 51 | + } |
| 52 | + |
| 53 | + private Node deserializeHelper(Queue<String> queue) { |
| 54 | + Node root = new Node(); |
| 55 | + root.val = Integer.parseInt(queue.remove()); |
| 56 | + int size = Integer.parseInt(queue.remove()); |
| 57 | + |
| 58 | + root.children = new ArrayList<>(size); |
| 59 | + |
| 60 | + for (int i = 0; i < size; i++) { |
| 61 | + root.children.add(deserializeHelper(queue)); |
| 62 | + } |
| 63 | + |
| 64 | + return root; |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +// Your Codec object will be instantiated and called as such: |
| 69 | +// Codec codec = new Codec(); |
| 70 | +// codec.deserialize(codec.serialize(root)); |
0 commit comments