Brushing Diary 01: Serializing and Deserializing Binary Trees

1. Conceptual understanding:

The topic is as follows: https://leetcode.cn/problems/xu-lie-hua-er-cha-shu-lcof/

What is serialization?

Serialization can be understood as the result of layer order traversal, that is, the information of all nodes is spliced ​​into a string according to the result of layer order traversal, but it is different from general layer order traversal: serialization needs to output All node information, and layer order traversal generally does not output null nodes. as follows:

2. Solutions:

1. Serialization:

Since there are similarities with layer order traversal, the solution ideas also have similarities:

When we solve the problem of hierarchical traversal, we generally use the auxiliary queue space, that is, create a LinkedList to store nodes, judge whether the current node is not empty, add it to the queue if it is not empty, and set a counter at the same time: continuously record the current queue There are several elements in , which will be output later, and the title and code are as follows:

https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

class Solution {
    public int[] levelOrder(TreeNode root) {
        if(root == null) return new int[0];
        Queue<TreeNode> queue = new LinkedList<>(){
    
    { add(root); }};
        ArrayList<Integer> ans = new ArrayList<>();
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            ans.add(node.val);
            if(node.left != null) queue.add(node.left);
            if(node.right != null) queue.add(node.right);
        }
        int[] res = new int[ans.size()];
        for(int i = 0; i < ans.size(); i++)
            res[i] = ans.get(i);
        return res;
    }
}

作者:jyd
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/solution/mian-shi-ti-32-i-cong-shang-dao-xia-da-yin-er-ch-4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Serialization does not need to set a counter, but the idea of ​​traversal is exactly the same as it, but serialization needs to use StringBuilder to splicing strings, that is, splicing elements put into the queue each time into StringBuilder, null also needs splicing, by judging the queue Whether it is empty, perform a continuous loop:

public String serialize(TreeNode root) {
        //检验头结点的合法性
        if(root == null) return "[]";
        //拼接左括号
        StringBuilder res = new StringBuilder("[");
        //将头结点接入
        Queue<TreeNode> queue = new LinkedList<>() {
    
    { add(root); }};
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            //由于null也需要加入队列,所以这时需判断加入队列的元素是否为null
            if(node != null) {
                //  将当前结点进行拼接
                res.append(node.val + ",");
                //
                queue.add(node.left);
                queue.add(node.right);
            }
            //如果是null直接在StringBuilder中拼接null
            else res.append("null,");
        }
        //将最后一个逗号删除
        res.deleteCharAt(res.length() - 1);
        //拼接右半部分括号
        res.append("]");
        return res.toString();

2. Deserialization

Deserialization can be understood as the reverse process of serialization: in the serialized string, new elements are continuously taken out according to the subscript, and whether it is empty is judged. If it is not empty, it is added to the auxiliary queue, and the loop continues until the elements in the queue are Empty: end of loop.

The code to implement the logic is as follows:

 public TreeNode deserialize(String data) {
        //如果序列化字符串中的元素为空,直接返回null
        if(data.equals("[]")) return null;
         //转化为字符串数组,便于节点的遍历
        String[] vals = data.substring(1, data.length() - 1).split(",");
        //先将第一个元素加入队列
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        Queue<TreeNode> queue = new LinkedList<>() {
    
    { add(root); }};
        int i = 1;
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            //以队列是否为空为不断循环的条件
            if(!vals[i].equals("null")) {
                //当前不为空则加入到队列,并将其作为当前元素的左子节点
                node.left = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.left);
            }
            i++;
            if(!vals[i].equals("null")) {
            //当前不为空则加入到队列,并将其作为当前元素的右子节点
                node.right = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.right);
            }
            i++;
        }
        //反序列化结束,返回根节点
        return root;
    }

Guess you like

Origin blog.csdn.net/m0_65431718/article/details/129460534