Advertisement
1988coder

428. Serialize and Deserialize N-ary Tree

Nov 27th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  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. /*
  16. Serialize function
  17. Time Complexity: O(M * K) = O(M * 11) = O(M)
  18. Space Complexity: O(M * K) = O(M * 11) = O(M)
  19. M = Number of Nodes
  20. K = Average Length of each node. (Bounded by 11)
  21.  
  22. Deserialize function
  23. Time Complexity: O(N + M + M*K) = O(N + M*K) = O(N+N) = O(N)
  24. Space Complexity: O(M * K) = O(N)
  25. N = Length of the input string
  26. M = Number of Nodes
  27. K = Average Length of each node. (Bounded by 11)
  28. */
  29. class Codec {
  30.  
  31.     // Encodes a tree to a single string.
  32.     public String serialize(Node root) {
  33.         List<String> list = new ArrayList();
  34.         if (root == null) {
  35.             return "";
  36.         }
  37.         serializeHelper(list, root);
  38.         return String.join(",", list);
  39.     }
  40.    
  41.     private void serializeHelper(List<String> list, Node node) {
  42.         if (node == null) {
  43.             return;
  44.         }
  45.         list.add(String.valueOf(node.val));
  46.         list.add(String.valueOf(node.children.size()));
  47.         for (Node child : node.children) {
  48.             serializeHelper(list, child);
  49.         }
  50.     }
  51.  
  52.     // Decodes your encoded data to tree.
  53.     public Node deserialize(String data) {
  54.         if (data == null || data.length() == 0) {
  55.             return null;
  56.         }
  57.         return deserializeHelper(new LinkedList<String>(Arrays.asList(data.split(","))));
  58.     }
  59.    
  60.     private Node deserializeHelper(Queue<String> queue) {
  61.         if (queue == null || queue.isEmpty()) {
  62.             return null;
  63.         }
  64.         Node node = new Node();
  65.         node.val = Integer.parseInt(queue.poll());
  66.         int noOfChildren = 0;
  67.         if (!queue.isEmpty()) {
  68.             noOfChildren = Integer.parseInt(queue.poll());
  69.         }
  70.         node.children = new ArrayList<Node>(noOfChildren);
  71.         for (int i = 0; i < noOfChildren; i++) {
  72.             node.children.add(deserializeHelper(queue));
  73.         }
  74.         return node;
  75.     }
  76. }
  77.  
  78. // Your Codec object will be instantiated and called as such:
  79. // Codec codec = new Codec();
  80. // codec.deserialize(codec.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement