【LeetCode 】: 297. 二叉树的序列化与反序列化

297. 二叉树的序列化与反序列化

问题描述:

序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。

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

题目链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

示例1

你可以将以下二叉树:
1
/
2 3
/
4 5
序列化为 “[1,2,3,null,null,4,5]”

思路:

序列化非常简单,直接使用层次遍历算法,拼凑出结果字符串,只需主意,在序列化最后,删除最后一个多余的逗号。本题的难点在于下面反序列化的过程。

同样利用队列,对字符串进行反序列化,首先去除[]符号,把元素提取出来。随后初始化队列,用一个下标index标记当前扫描到字符串的哪个部位。把字符串的第一个节点入队。然后判断循环,如果队列不空,令队头出队,然后把出队节点的左节点和右节点分别赋值为字符串的前两个元素。这样就实现了对一个节点左孩子和右孩子的提取。之后,如果左孩子不为空,把左孩子入队,如果右孩子不为空,把右孩子入队。即可实现反序列化。

完整代码:

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null)
            return "[]";
        StringBuffer res = new StringBuffer("[");
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if(tmp != null) {
                res.append(tmp.val + ",");
                queue.add(tmp.left);
                queue.add(tmp.right);
            }else {
                res.append("null,");
            }
        }
        return res.substring(0 , res.length() - 1) + "]";
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null && data.equals("[]"))
            return null;
        String res = data.substring(1 , data.length() - 1);
        String values[] = res.split(",");
        int index = 0;
        TreeNode node = getTreeNode(values[index++]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(node);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            tmp.left = getTreeNode(values[index++]);
            tmp.right = getTreeNode(values[index++]);
            if (tmp.left != null) {
                queue.add(tmp.left);
            }
            if (tmp.right != null)
                queue.add(tmp.right);

        }
        return node;
    }

    public TreeNode getTreeNode(String s) {
        if(s.equals("null"))
            return null;
        return new TreeNode(Integer.valueOf(s));

    }

附加GitHub链接

发布了19 篇原创文章 · 获赞 30 · 访问量 6370

猜你喜欢

转载自blog.csdn.net/qq_36008321/article/details/104642294
今日推荐