Skip to content

Latest commit

 

History

History
executable file
·
187 lines (173 loc) · 5.44 KB

297. Serialize and Deserialize Binary Tree.md

File metadata and controls

executable file
·
187 lines (173 loc) · 5.44 KB

297. Serialize and Deserialize Binary Tree

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));

Third Time

  • Method 1: dfs
    /**
     * 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 EMPTY = "#";
        private static final String SPLIT = ",";
        // 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[] tokens = data.split(SPLIT);
            LinkedList<String> q = new LinkedList<>();
            q.addAll(Arrays.asList(tokens));
            return deserialize(q);
        }
        private TreeNode deserialize(LinkedList<String> q){
            String token = q.poll();
            if(token.equals(EMPTY)) return null;
            else{
                TreeNode node = new TreeNode(Integer.parseInt(token));
                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));