LeetCode 297. Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)

原题网址:https://leetcode.com/problems/serialize-and-deserialize-binary-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 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.

方法一:深度优先+递归。

/**
 * 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.printf("serialize: %s\n", sb.toString());
        return sb.toString();
    }

    private int pos;
    private TreeNode parse(String data) {
        if (data.charAt(pos) != '[') return null;
        pos ++;
        if (data.charAt(pos) == ']') {
            pos ++;
            return null;
        }
        int val = 0;
        boolean negative = false;
        if (data.charAt(pos) == '-') {
            negative = true;
            pos ++;
        }
        for(;pos='0' && data.charAt(pos)<='9'; pos ++) {
            val = val*10+data.charAt(pos)-'0';
        }
        if (negative) val = -val;
        TreeNode node = new TreeNode(val);
        // System.out.printf("val=%d\n", val);
        if (data.charAt(pos) != ',') return null;
        pos ++;
        node.left = parse(data);
        if (data.charAt(pos) != ',') return null;
        pos ++;
        node.right = parse(data);
        if (data.charAt(pos) != ']') return null;
        pos ++;
        return node;
    } 
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        pos = 0;
        return parse(data);
    }
}

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

方法二:广度优先。

/**
 * 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 "null";
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        LinkedList list = new LinkedList<>();
        list.add(root.left);
        list.add(root.right);
        while (!list.isEmpty()) {
            TreeNode node = list.remove();
            sb.append(",");
            if (node == null) sb.append("null");
            else {
                sb.append(node.val);
                list.add(node.left);
                list.add(node.right);
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        int pos = 0;
        pos = parse(data, pos);
        TreeNode root = parsed;
        if (root == null) return null;
        LinkedList nodes = new LinkedList<>();
        nodes.add(root);
        do {
            TreeNode node = nodes.remove();
            pos = parse(data, pos);
            node.left = parsed;
            if (node.left != null) nodes.add(node.left);
            pos = parse(data, pos);
            node.right = parsed;
            if (node.right != null) nodes.add(node.right);
        } while (!nodes.isEmpty());
        return root;
    }
    
    private TreeNode parsed;
    private int parse(String data, int pos) {
        if (data.charAt(pos) == 'n') {
            pos += 4;
            if (pos= '0' && data.charAt(pos) <= '9'; pos ++) {
            val = val * 10 + data.charAt(pos) - '0';
        }
        if (pos

方法三:广度优先,按层进行序列化。

/**
 * 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) {
        StringBuilder sb = new StringBuilder();
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            if (sb.length()>0) sb.append(",");
            if (node == null) sb.append("#");
            else {
                sb.append(node.val);
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if ("#".equals(data)) return null;
        String[] vals = data.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        for(int i=1; i


你可能感兴趣的:(二叉树,树,序列化,反序列化,持久化,递归,深度优先搜索,广度优先搜索,文本解析,上下文,嵌套,leetcode)