Leetcode-Serialize and Deserialize Binary Tree(Java)

Question:

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

  1
 / \
2   3
   / \
  4   5

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.

Thinking:

There are serveral thinkings emerged in my mind when I first saw this question. Firstly, I want to finishi the normal method which is the same as the Leetcode presenting. But it is LTE. Then I searched on the Internet and found my solution’s lack and then solved it.

Solution:

Previous Code:

//normal method
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
    String res = "";
    if (root == null)
        return res;
    Queue<TreeNode> q = new LinkedList<TreeNode>();
    q.add(root);
    res += root.val + ",";
    while (!q.isEmpty()){
        int num = q.size();
        String nullstr = "";
        while (num > 0){
            TreeNode n = q.poll();
            if (n.left != null){
                q.add(n.left);
                res += nullstr + n.left.val + ",";
            }
            else{
                nullstr += "null,";
            }
            if (n.right != null){
                q.add(n.right);
                res += nullstr + n.right.val + ",";
            }
            else{
                nullstr += "null,";
            }
            num--;
        }
    }

    return res;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
    TreeNode root;
    if(data.length() == 0)
        return null;
    String[] strs = data.split(",");
    root = new TreeNode(Integer.parseInt(strs[0]));
    bfs(root, strs, 1, true);
    bfs(root, strs, 2, false);

    return root;
}
private void bfs(TreeNode node, String[] strs, int index, boolean left){
    if (index >= strs.length)
        return;
    if (strs[index].equals("null"))
        return;
    TreeNode newNode = new TreeNode(Integer.parseInt(strs[index]));
    if (left){
        node.left = newNode;
    }
    else{
        node.right = newNode;
    }
    bfs(newNode, strs, index*2+1, true);
    bfs(newNode, strs, index*2+2, false);
}

Reference Code(http://blog.csdn.net/ljiabin/article/details/49474445):

public String serialize(TreeNode root) {
    StringBuilder sb = new StringBuilder();

    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        if (node == null) {
            sb.append("null,");
        } else {
            sb.append(String.valueOf(node.val) + ",");
            queue.offer(node.left);
            queue.offer(node.right);
        }
    }

    return sb.toString();
}

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

    String[] vals = data.split(",");
    int[] nums = new int[vals.length];
    TreeNode[] nodes = new TreeNode[vals.length];

    for (int i = 0; i < vals.length; i++) {
        if (i > 0) {
            nums[i] = nums[i - 1];
        }
        if (vals[i].equals("null")) {
            nodes[i] = null;
            nums[i]++;
        } else {
            nodes[i] = new TreeNode(Integer.parseInt(vals[i]));
        }
    }

    for (int i = 0; i < vals.length; i++) {
        if (nodes[i] == null) {
            continue;
        }
        nodes[i].left = nodes[2 * (i - nums[i]) + 1];
        nodes[i].right = nodes[2 * (i - nums[i]) + 2];
    }

    return nodes[0];
}

}