428.Serialize-and-Deserialize-N-ary-Tree

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]]. Note that this is just an example, you do not necessarily need to follow this format.

Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.

For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

You do not necessarily need to follow the above suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.

Constraints:
The height of the n-ary tree is less than or equal to 1000
The total number of nodes is between [0, 10^4]
Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.

代码

Approach #0: Preorder recursive Using queue

class Codec {
    // Encodes a tree to a single string.
    public String serialize(Node root) {
        List<String> list = new LinkedList<>();
        serializeHelper(root, list);
        return String.join(",", list);
    }

    private void serializeHelper(Node root, List<String> list) {
        if (root == null) {
            return;
        } else {
            list.add(String.valueOf(root.val));
            list.add(String.valueOf(root.children.size()));
            for (Node child: root.children) {
                serializeHelper(child, list);
            }
        }
    }

    // Decodes your encoded data to tree.
    public Node deserialize(String data) {
        if (data.isEmpty())   return null;

        String[] ss = data.split(",");
        Queue<String> q = new LinkedList<>(Arrays.asList(ss));
        return deserializeHelper(q);
    }

    private Node deserializeHelper(Queue<String> q) {
        Node root = new Node();
        root.val = Integer.parseInt(q.poll());
        int size = Integer.parseInt(q.poll());
        root.children = new ArrayList<Node>(size);
        for (int i = 0; i < size; i++){
            root.children.add(deserializeHelper(q));
        }
        return root;
    }
}

Approach #2 DFS with a Sentinel

class Codec {
    class WrappableInt {
        private int value;
        public WrappableInt(int x) {
            this.value = x;
        }
        public int getValue() {
            return this.value;
        }
        public void increment() {
            this.value++;
        }
    }

    // Encodes a tree to a single string.
    public String serialize(Node root) {

        StringBuilder sb = new StringBuilder();
        this._serializeHelper(root, sb);
        return sb.toString();
    }

    private void _serializeHelper(Node root, StringBuilder sb) {

        if (root == null) {
            return;
        }

        // Add the value of the node
        sb.append((char) (root.val + '0'));

        // Recurse on the subtrees and build the 
        // string accordingly
        for (Node child : root.children) {
            this._serializeHelper(child, sb);
        }

        // Add the sentinel to indicate that all the children
        // for the current node have been processed
        sb.append('#');
    }

    // Decodes your encoded data to tree.
    public Node deserialize(String data) {
        if (data.isEmpty())
            return null;

        return this._deserializeHelper(data, new WrappableInt(0));
    }

    private Node _deserializeHelper(String data, WrappableInt index) {  

        if (index.getValue() == data.length()) {
            return null;
        }

        Node node = new Node(data.charAt(index.getValue()) - '0', new ArrayList<Node>());
        index.increment();
        while (data.charAt(index.getValue()) != '#') {
            node.children.add(this._deserializeHelper(data, index));
        }

        // Discard the sentinel. Note that this also moves us
        // forward in the input string. So, we don't have the index
        // progressing inside the above while loop!
        index.increment();

        return node;
    }
}

Approach #3 Level order traversal

class Codec {
    // Encodes a tree to a single string.
    public String serialize(Node root) {
        if (root == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        this._serializeHelper(root, sb);
        return sb.toString();
    }

    private void _serializeHelper(Node root, StringBuilder sb) {
        // Queue to perform a level order traversal of the tree
        Queue<Node> q = new LinkedList<Node>();

        // Two dummy nodes that will help us in serialization string formation.
        // We insert the "endNode" whenever a level ends and the "childNode"
        // whenever a node's children are added to the queue and we are about
        // to switch over to the next node.
        Node endNode = new Node();
        Node childNode = new Node();
        q.add(root);
        q.add(endNode);

        while (!q.isEmpty()) {
            // Pop a node
            Node node = q.poll();
            // If this is an "endNode", we need to add another one
            // to mark the end of the current level unless this
            // was the last level.
            if (node == endNode) {
                // We add a sentinal value of "#" here
                sb.append('#');
                if (!q.isEmpty()) {
                    q.add(endNode);  
                }
            } else if (node == childNode) {
                // Add a sentinal value of "$" here to mark the switch to a
                // different parent.
                sb.append('$');
            } else {
                // Add value of the current node and add all of it's
                // children nodes to the queue. Note how we convert
                // the integers to their corresponding ASCII counterparts.
                sb.append((char) (node.val + '0'));
                for (Node child : node.children) {
                    q.add(child);
                }

                // If this not is NOT the last one on the current level, 
                // add a childNode as well since we move on to processing
                // the next node.
                if (q.peek() != endNode) {
                    q.add(childNode);
                }
            }
        }
    }

    // Decodes your encoded data to tree.
    public Node deserialize(String data) {
        if (data.isEmpty()) {
            return null;
        }

        Node rootNode = new Node(data.charAt(0) - '0', new ArrayList<Node>());
        this._deserializeHelper(data, rootNode);
        return rootNode;
    }

    private void _deserializeHelper(String data, Node rootNode) {  
        // We move one level at a time and at every level, we need access
        // to the nodes on the previous level as well so that we can form
        // the children arrays properly. Hence two arrays.
        LinkedList<Node> currentLevel = new LinkedList<Node>();
        LinkedList<Node> prevLevel = new LinkedList<Node>();
        currentLevel.add(rootNode);
        Node parentNode = rootNode;

        // Process the characters in the string one at a time.
        for (int i = 1; i < data.length(); i++) {
            char d = data.charAt(i);
            if (d == '#') {
                // Special processing for end of level. We need to swap the
                // array lists. Here, we simply re-initialize the "currentLevel"
                // arraylist rather than clearing it.
                prevLevel = currentLevel;
                currentLevel = new LinkedList<Node>();

                // Since we move one level down, we take the parent as the first
                // node on the current level.
                parentNode = prevLevel.poll();
            } else if (d == '$') {
                // Special handling for change in parent on the same level
                  parentNode = prevLevel.poll();
              } else {
                  Node childNode = new Node(d - '0', new ArrayList<Node>());    
                  currentLevel.add(childNode);
                  parentNode.children.add(childNode);
              }
        }
    }
}

Approach 1: DFS with Children Sizes

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Codec {
  class WrappableInt {
    private int value;
    public WrappalbeInt(int x) {
      this.value = x;
    }
    public int getValue() {
      return this.value;
    }
    public void increment() {
      this.value++;
    }
  }

  // Encodes a tree to a single string.
  public String serialize(Node root) {
        StringBuilder sb = new StringBuilder();
    this._serializeHelper(root, sb);
    return sb.toString();
  }

  private void _serializeHelper(Node root, StringBuilder sb) {
    if (root == null)    return;

    sb.append((char) (root.val + '0'));
    sb.append((char) (root.children.size() + '0'));
    for (Node child : root.children) {
      this._serializeHelper(child, sb);
    }
  }

  // Decodes your encoded data to tree.
  public Node deserialize(String data) {
        if (data.isEmpty()) return null;

    return this._deserializeHelper(data, new WrappableInt(0));
  }

  private Node _deserializeHelper(String data, WrappableInt index) {
    if (index.getValue() == data.length()) {
      return null;
    }

    Node node = new Node(data.charAt(index.getValue() - '0', new ArrayList<Node)());
    index.increment();
    int numChildren = data.charAt(index.getValue() - '0');
    for (int i = 0; i < numChildren; i++) {
      index.increment();
      node.children.add(this._deserializeHelper(data, index));
    }

    return node;
  }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Last updated