Java二叉树的序列化与反序列化

        请实现两个函数,分别用来序列化和反序列化二叉树。

        你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。

/**
 * 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 res = new StringBuilder();
        res.append("[");
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while( !queue.isEmpty() ){
            TreeNode temp = queue.poll();
            if(temp != null){
                res.append(temp.val + ",");
                queue.add(temp.left);
                queue.add(temp.right);
            }else{
                res.append("null,");
            }
        }
        res.deleteCharAt(res.length()-1);
        res.append("]");
        return res.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("[]")){
            return null;
        }
        String[] vals = data.substring(1,data.length()-1).split(",");

        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        int i = 1;
        while( !queue.isEmpty() ){
            TreeNode temp = queue.poll();
            if( !vals[i].equals("null") ){
                temp.left = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(temp.left);
            }++i;
            if( !vals[i].equals("null") ){
                temp.right = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(temp.right);
            }++i;

        }

        return root;
    }
}

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

执行用时:19 ms, 在所有 Java 提交中击败了55.68%的用户

内存消耗:43.7 MB, 在所有 Java 提交中击败了48.64%的用户

通过测试用例:48 / 48

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值