LeetCode 剑指 Offer 37. 序列化二叉树

Posted Zephyr丶J

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 剑指 Offer 37. 序列化二叉树相关的知识,希望对你有一定的参考价值。

剑指 Offer 37. 序列化二叉树

2021.6.30 每日一题,六月徽章get,只不过时间过得太快了!

题目描述

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

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

提示:输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。

 
示例:

在这里插入图片描述

输入:root = [1,2,3,null,null,4,5]
输出:[1,2,3,null,null,4,5]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

层序遍历,遍历到的空节点添加null

/**
 * 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) {
        StringBuffer sb = new StringBuffer();
        if(root == null)
            return "null";
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        sb.append(root.val + ",");
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size-- > 0){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                    sb.append(node.left.val + ",");
                }else{
                    sb.append("null,");
                }
                if(node.right != null){
                    queue.offer(node.right);
                    sb.append(node.right.val + ",");
                }else{
                    sb.append("null,");
                }
            }
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if("null".equals(data))
            return null;
        String[] ss = data.split(",");
        TreeNode root = new TreeNode(Integer.valueOf(ss[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int index = 1;
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size-- > 0){
                TreeNode node = queue.poll();
                if(!"null".equals(ss[index])){
                    TreeNode leftnode = new TreeNode(Integer.valueOf(ss[index]));
                    node.left = leftnode;
                    queue.offer(leftnode);
                }
                index++;
                if(!"null".equals(ss[index])){
                    TreeNode rightnode = new TreeNode(Integer.valueOf(ss[index]));
                    node.right = rightnode;
                    queue.offer(rightnode);
                }
                index++;
            }
        }
        return root;
    }
}

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

现在写bfs习惯性的先计算size了,其实有的问题没有必要

/**
 * 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) {
        StringBuffer sb = new StringBuffer();
        if(root == null)
            return "null";
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node != null){
                queue.offer(node.left);
                queue.offer(node.right);
                sb.append(node.val + ",");
            }else{
                sb.append("null,");
            }
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if("null".equals(data))
            return null;
        String[] ss = data.split(",");
        TreeNode root = new TreeNode(Integer.valueOf(ss[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int index = 1;
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(!"null".equals(ss[index])){
                TreeNode leftnode = new TreeNode(Integer.valueOf(ss[index]));
                node.left = leftnode;
                queue.offer(leftnode);
            }
            index++;
            if(!"null".equals(ss[index])){
                TreeNode rightnode = new TreeNode(Integer.valueOf(ss[index]));
                node.right = rightnode;
                queue.offer(rightnode);
            }
            index++;
        }
        return root;
    }
}

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

    // Decodes your encoded data to tree.
    //遍历的下标
    int index = 0;
    public TreeNode deserialize(String data) {
        if("null".equals(data))
            return null;
        String[] ss = data.split(",");
        return deserialize(ss);
    }

    public TreeNode deserialize(String[] ss){
        if("null".equals(ss[index])){
            index++;
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(ss[index++]));
        node.left = deserialize(ss);
        node.right = deserialize(ss);
        return node;
    }
}

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

或者说不用全局的index变量,而是把String数组写到一个集合中(Arrays.asList(s)),然后递归过程中对集合的元素进行弹出

	public TreeNode deserialize(String data) {
        //反序列化应该也是递归
        String[] s = data.split(",");
        Queue<String> queue = new LinkedList<>(Arrays.asList(s));
        return deserialize(queue);
    }

    public TreeNode deserialize(Queue<String> queue){
        String val = queue.poll();
        if("null".equals(val)){
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(val));
        node.left = deserialize(queue);
        node.right = deserialize(queue);
        return node;
    }

以上是关于LeetCode 剑指 Offer 37. 序列化二叉树的主要内容,如果未能解决你的问题,请参考以下文章

剑指 Offer 37. 序列化二叉树

LeetCode1734. 解码异或后的排列 / 剑指 Offer 36. 二叉搜索树与双向链表 / 剑指 Offer 37. 序列化二叉树

LeetCode 剑指Offer 37 序列化二叉树[BFS 二叉树] HERODING的LeetCode之路

剑指 Offer 37. 序列化二叉树

剑指Offer 37 - 序列化与反序列化二叉树

剑指 Offer 37. 序列化二叉树