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.

Example:

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]"

Thinking:

  • Method 1: 使用了额外内存,cheating
    • [1,[2,[],[]],[3,[4,[],[]],[5,[],[]]]]
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "[]";
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(root.val);
        sb.append(",");
        sb.append(serialize(root.left));
        sb.append(",");
        sb.append(serialize(root.right));
        sb.append("]");
        System.out.println(sb.toString());
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    private int pos = 0;
    public TreeNode deserialize(String data) {
        char[] arr = data.toCharArray();
        if(arr[pos++] != '[') return null;
        if(arr[pos] == ']'){
            pos++;
            return null;
        }
        StringBuilder num = new StringBuilder();
        while(arr[pos] != ','){
            num.append(arr[pos++]);
        }
        pos++;
        TreeNode cur = new TreeNode(Integer.valueOf(num.toString()));
        cur.left = deserialize(data);
        if(arr[pos++] != ',') return null;
        cur.right = deserialize(data);
        if(arr[pos++] != ']') return null;
        return cur;
    }
}

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

Second time

Imgur

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    private final String split = ",";
    private final String empty = "#";
    
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }
    private void serialize(TreeNode node, StringBuilder sb){
        if(node == null){
            sb.append(empty).append(split);
        }else{
            sb.append(node.val).append(split);
            serialize(node.left, sb);
            serialize(node.right, sb);
        }
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] nodes = data.split(split);
        LinkedList<String> q = new LinkedList<>();
        q.addAll(Arrays.asList(nodes));
        return deserialize(q);
    }
    private TreeNode deserialize(LinkedList<String> q){
        String val = q.poll();
        if(val.equals(empty)){
            return null;
        }else{
            TreeNode node = new TreeNode(Integer.parseInt(val));
            node.left = deserialize(q);
            node.right = deserialize(q);
            return node;
        }
    }
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Amazon session

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    private static final String split = ",";
    private static final String NULL = "#";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }
    private void serialize(TreeNode node, StringBuilder sb){
        if(node == null) sb.append(NULL + split);
        else{
            sb.append("" + node.val + split);
            serialize(node.left, sb);
            serialize(node.right, sb);
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] tokens = data.split(split);
        Queue<String> q = new LinkedList<>();
        for(String token : tokens) q.offer(token);
        return deserialize(q);
    }
    private TreeNode deserialize(Queue<String> q){
        String token = q.poll();
        if(token.equals(NULL)) return null;
        int val = Integer.parseInt(token);
        TreeNode node = new TreeNode(val);
        node.left = deserialize(q);
        node.right = deserialize(q);
        return node;
    }
}

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