剑指 Offer 37. 序列化二叉树

剑指 Offer 37. 序列化二叉树

难度困难

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

示例: 

你可以将以下二叉树:

1

/ \

2 3

/ \

4 5

序列化为 "[1,2,3,null,null,4,5]"

注意:本题与主站 297 题相同:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

/**

* 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("[");

            Queue<TreeNode> queue = new LinkedList<>();

            queue.add(root);

            while (!queue.isEmpty()) {

                TreeNode treeNode = queue.poll();

                if (treeNode == null) {

                    sb.append("null,");

                } else {

                    sb.append(treeNode.val).append(",");

                    queue.add(treeNode.left);

                    queue.add(treeNode.right);

                }

            }

            sb.deleteCharAt(sb.length() - 1);

            sb.append("]");

            return sb.toString();

        }

        // Decodes your encoded data to tree.

        public TreeNode deserialize(String data) {

            if (data == "[]") {

                return null;

            }

            String[] strings = data.substring(1, data.length() - 1).split(",");

            TreeNode root = new TreeNode(Integer.parseInt(strings[0]));

            Queue<TreeNode> queue = new LinkedList<>();

            queue.add(root);

            int i = 1;

            while (!queue.isEmpty()) {

                TreeNode treeNode = queue.poll();

                 if (!strings[i].equals("null")) {

                    treeNode.left = new TreeNode(Integer.parseInt(strings[i]));

                    queue.add(treeNode.left);

                }

                i++;

                if (!strings[i].equals("null")) {

                    treeNode.right = new TreeNode(Integer.parseInt(strings[i]));

                    queue.add(treeNode.right);

                }

                i++;

            }

            return root;

        }

}

// Your Codec object will be instantiated and called as such:

// Codec codec = new Codec();

// codec.deserialize(codec.serialize(root));

上一篇:剑指 Offer 37. 序列化二叉树 二叉树 字符串


下一篇:6-37 mystrcat (20 分)