LeetCode 297. Serialize and Deserialize Binary Tree【Java】

题目描述

二叉树的序列化和反序列化

AC代码

题目中说到,不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。 序列化和反序列化的时候是不会将它们进行序列化的,虽然解题里用了也没啥问题,但是应该注意,之前做的都是使用了全局变量的,这次给出不需要使用全局变量的做法↓,此题解法不唯一噢!

/**
 * 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 "#,";
        }
        String str=root.val+",";
        str+=serialize(root.left);
        str+=serialize(root.right);
        return str;
    }


    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        int u[]={0};
        return dfsDeser(data,u);
    }


    TreeNode dfsDeser(String data,int u[]){
        if(u[0]==data.length()) return null;
        int k=u[0];
        while(data.charAt(k)!=',') k++;
        if(data.charAt(u[0])=='#'){
            //跳过#和,
            u[0]+=2;
            return null;
        }
        int t=0;
        //判断负数
        boolean is_minus=false;
        if(data.charAt(u[0])=='-') {
            is_minus=true;
            u[0]++;
        }
        //计算val值
        for(int i=u[0];i<k;i++){
            t=t*10+data.charAt(i)-'0';
        }
        if(is_minus)
            t=-t;
        //跳过逗号    
        u[0]=k+1;
        TreeNode root=new TreeNode(t);
        root.left=dfsDeser(data,u);
        root.right=dfsDeser(data,u);
        return root;
    }
}

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

除此之外,还可以通过队列的方式完成序列化和反序列化。

发布了201 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40992982/article/details/105480196