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<data.length() && data.charAt(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<TreeNode> 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<TreeNode> 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<data.length()) pos ++;
            parsed = null;
            return pos;
        }
        boolean negative = false;
        int val = 0;
        if (data.charAt(pos) == '-') {
            negative = true;
            pos ++;
        }
        for(; pos<data.length() && data.charAt(pos) >= '0' && data.charAt(pos) <= '9'; pos ++) {
            val = val * 10 + data.charAt(pos) - '0';
        }
        if (pos<data.length()) pos ++;
        if (negative) val = -val;
        parsed = new TreeNode(val);
        return pos;
    }
}

// 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) {
        StringBuilder sb = new StringBuilder();
        LinkedList<TreeNode> 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<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        for(int i=1; i<vals.length; i+=2) {
            TreeNode node = queue.remove();
            if (!"#".equals(vals[i])) {
                TreeNode left = new TreeNode(Integer.parseInt(vals[i]));
                node.left = left;
                queue.add(left);
            }
            if (!"#".equals(vals[i+1])) {
                TreeNode right = new TreeNode(Integer.parseInt(vals[i+1]));
                node.right = right;
                queue.add(right);
            }
        }
        return root;
    }
}

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值