297. Serialize and Deserialize Binary Tree

Hard (LinkedIn, Google, Uber, Facebook, Amazon, Microsoft, Yahoo, Bloomberg)

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 a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary 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 tree

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

public class Codec {

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

    Queue<TreeNode> queue = new LinkedList<>();
    int lastPos = 0;
    StringBuilder builder = new StringBuilder();
    queue.offer(root);

    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();

        if (node == null) {
            builder.append("#,");
        } else {
            builder.append(node.val).append(",");
            lastPos = builder.length() - 1;
            queue.offer(node.left);
            queue.offer(node.right);
        }
    }

    return builder.substring(0, lastPos);
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
    if (data == null || data.length() == 0) {
        return null;
    }

    String[] nodes = data.split(",");

    if (nodes.length == 0 || nodes[0].equals("#")) {
        return null;
    }

    TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
    List<TreeNode> list = new ArrayList<>();
    list.add(root);
    int index = 0;

    for (int i = 1; i < nodes.length; i++) {
        if (!nodes[i].equals("#")) {
            TreeNode node = new TreeNode(Integer.parseInt(nodes[i]));

            if (i % 2 == 1) {
                list.get(index).left = node;
            } else {
                list.get(index).right = node;
            }

            list.add(node);
        }

        if (i % 2 == 0) {
            index++;
        }
    }

    return root;
}

}

results matching ""

    No results matching ""