Sword finger Offer II 048 Serialization and deserialization binary tree

Posted by refined on Fri, 14 Jan 2022 06:05:01 +0100

Serialization is the operation of converting a data structure or object into continuous bits, and then the converted data can be stored in a file or memory. At the same time, it can also be transmitted to another computer environment through the network, and the original data can be reconstructed in the opposite way.

Please 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.

Example 1:

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

Input: root = []
Output: []
Example 3:

Input: root = [1]
Output: [1]
Example 4:

Input: root = [1,2]
Output: [1,2]

Tips:

The input / output format is the same as that currently used by LeetCode. For details, see 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.
The number of nodes in the tree is in the range [0, 104]
-1000 <= Node.val <= 1000

Note: this question is the same as question 297 of the main station: https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

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

In fact, the essence is a hierarchical traversal, but some details need to be paid attention to. For example, when converting a string to a binary tree, first divide the array according to the, and then traverse the input. If it is not empty, create a new node and install the left and right subtrees, otherwise jump directly

When converting a binary tree to a string, remember that the position of [] and must not be wrong. null can also join the team and can be assigned normally. You need to judge.

/**
 * 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.offer(root);
        int count = 0;
        while(!queue.isEmpty()) {
            if (queue.peek() == null) {
                if (count == 0) {
                    sb.append("null");
                    count = 1;
                } else {
                    sb.append(",null");
                }
                queue.poll();
            } else {
                TreeNode t = queue.poll();
                if (count == 0) {
                    sb.append(t.val + "");
                    count = 1;
                } else {
                    sb.append("," + t.val);
                }
                queue.offer(t.left);
                queue.offer(t.right);
            }

        }
        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(",");
        TreeNode root = new TreeNode(Integer.parseInt(datas[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int i = 1;
        while (!queue.isEmpty()) {
            TreeNode t = queue.poll();
            if (!datas[i].equals("null")) {
                t.left = new TreeNode(Integer.parseInt(datas[i]));
                queue.offer(t.left);
            }
            i++;
            if (!datas[i].equals("null")) {
                t.right = new TreeNode(Integer.parseInt(datas[i]));
                queue.offer(t.right);
            }
            i++;

        }
        return root;
    }
}

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

Topics: Java Algorithm leetcode