Sword finger Offer 37 Serialized binary tree

Please implement two functions to serialize and deserialize the binary tree respectively.

You need to design an algorithm to realize the serialization and deserialization of binary tree. There is no restriction on the execution logic of your sequence / deserialization algorithm. You only need to ensure that a binary tree can be serialized into a string and deserialize the string into the original tree structure.

Note: the input / output format is the same as that currently used by LeetCode. For details, please refer to the format of LeetCode serialized binary tree. You don't have to take this approach, you can also take other methods to solve the problem.

Example:

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Source: LeetCode
Link: https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Serialization and deserialization are actually converting binary tree into String and String into tree structure. First, serialization:
As the topic is not limited to the execution logic of sequence (inverse sequence), we use hierarchical traversal to execute. Like hierarchical traversal, we define the queue and define the StringBuilder class to add. When a node is not empty, StringBuilder adds the value of the node and adds the left and right nodes into the queue. When it is empty, we directly add null. Note:
Before defining StringBuilder, you need to insert "[", some small details.

Deserialization is to convert a String string into a binary tree. First, use split to convert the String class into an array, so that each index of the array is a node. Define i as the index position, and root as the first element of the array. Define the queue. When an index position of the first array is not empty, let the left subtree of the current node point to the new node, and i go back at the same time, And the new node joins the team, which is the same as the right node.

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

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

    }
}

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

Keywords: Java Algorithm leetcode queue Binary tree

Added by AngusL on Tue, 04 Jan 2022 23:05:31 +0200