LeetCode 449. Serialize and Deserialize BST [tree, BFS, DFS, stack] difficult

This article belongs to one of the series of articles "Conquering LeetCode". This series officially started on 2021/08/12. Since some questions on LeetCode are locked, this series will continue at least until all unlocked questions are cleared; since LeetCode is still creating new questions, the end date of this series may be forever. In this series of problem-solving articles, I will not only explain a variety of problem-solving ideas and their optimization, but also use a variety of programming languages ​​to solve the problems. When it comes to general solution methods, I will also summarize the corresponding algorithm templates.

In order to facilitate running, debugging and sharing code files on PC, I also established a related warehouse: https://github.com/memcpy0/LeetCode-Conquest . In this warehouse, you can not only see the link to the original LeetCode question, solution code, link to the solution article, summary of similar questions, summary of common solutions, etc., but also important information such as the frequency of original questions and related companies. If you have other preferred solutions, you can share them with others.

Since the content of this series of articles may be updated and changed at any time, you are welcome to follow and save the article Table of Contents of the Conquering LeetCode series of articles as a reminder.

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted over a network connection link for later reconstruction in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree . There are no restrictions on how the serialization/deserialization algorithm works. You just need to make sure that the binary search tree can be serialized to a string, and that the string can be deserialized into the original binary search tree.

The encoded string should be as compact as possible.

Example 1:

输入:root = [2,1,3]
输出:[2,1,3]

Example 2:

输入:root = []
输出:[]

hint:

  • The range of the number of nodes in the tree is[0, 10^4]
  • 0 <= Node.val <= 10^4
  • Question data guarantee : The input tree is a binary search tree.

Similar topics:

Binary search tree is a special binary tree. The serialization and deserialization process can also directly use the method in " 297. Serialization and Deserialization of Binary Trees ", that is, we can ignore the "BST" condition in implementation. , use BFS or DFS to store empty nodes for serial numbers and deserialization. Since the number of points is 1 e 4 1e41 e 4. In the worst case, when BST is chained, there will be a large waste of space.

But the special thing about binary search trees is that the in-order traversal is ordered , and this can be used to optimize time and space complexity.


Solution binary search tree + postorder traversal + stack

Given a binary tree, "pre-order traversal" and "in-order traversal" can restore the binary tree. Given a binary tree, "post-order traversal" and "in-order traversal" can also restore the binary tree. For binary search trees, given "pre-order traversal" or "post-order traversal", "in-order traversal" can be obtained by sorting them. therefore,Only performing "pre-order traversal" or "post-order traversal" on the binary search tree can meet the serialization and deserialization requirements. This problem is solved using the method of "post-order traversal"

  • When serializing, you only need to perform post-order traversal of the binary search tree (note that empty nodes are skipped), and then encode the array into a string.
  • When deserializing, the string needs to be decoded into an array for post-order traversal . When restoring the array traversed in post-order into a binary search tree, there is no need to sort the array traversed in in-order first , and then restore the binary tree based on the arrays traversed in in-order and post-order. Instead, the array can be directly traversed in post-order according to the order. Restore the binary search tree from the traversed array - in the array obtained by post-order traversal, the value of the root node is at the end of the array, the nodes of the left subtree are all smaller than the value of the root node, and the nodes of the right subtree are all greater than the value of the root node. , a recursive function can be designed to restore the binary search tree based on these properties.
public class Codec {
    
    
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
    
    
        return postOrder(root, new StringBuilder()).toString();
    }
    private StringBuilder postOrder(TreeNode root, StringBuilder sb) {
    
    
        if (root != null) {
    
     // 可以不用存储空指针
            sb = postOrder(root.left, sb);
            sb = postOrder(root.right, sb);
            sb.append(String.valueOf(root.val) + ",");
        }
        return sb;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
    
    
        if (data.isEmpty()) return null;
        String[] arr = data.split(",");
        Deque<Integer> stack = new ArrayDeque<Integer>();
        int length = arr.length;
        for (int i = 0; i < length; ++i)
            stack.push(Integer.parseInt(arr[i]));
        return construct(Integer.MIN_VALUE, Integer.MAX_VALUE, stack);
    }
    // 使用栈和后序遍历重构二叉搜索树
    private TreeNode construct(int lower, int upper, Deque<Integer> stack) {
    
    
        // 当前元素超出范围,不能用作子树根节点的值
        if (stack.isEmpty() || stack.peek() < lower || stack.peek() > upper) return null;
        int val = stack.pop();
        TreeNode root = new TreeNode(val);
        root.right = construct(val, upper, stack);
        root.left = construct(lower, val, stack);
        return root;
    }
}

Complexity analysis:

  • Time complexity: O ( n ) O(n)O ( n ) , of whichnnn is the number of nodes of the tree. serialize serializeser ia l i ze demandO ( n ) O(n)O ( n ) time to traverse each point. deserialize deserialized eser ia l i ze demandO ( n ) O(n)O ( n ) time to recover each point
  • Space complexity: O ( n ) O(n)O ( n ) , of whichnnn is the number of nodes of the tree. serialize serializeser ia l i ze demandO ( n ) O(n)O ( n ) space uses an array to store the value of each point, and the deepest recursion depth isO ( n ) O(n)O ( n )deserialize deserialized eser ia l i ze demandO ( n ) O(n)O ( n ) space uses an array to store the value of each point, and the deepest recursion depth isO ( n ) O(n)O ( n )

Guess you like

Origin blog.csdn.net/myRealization/article/details/132779776