LeetCode [449] serialization and de-serialization binary search tree

Title:
Serialization is the process of converting a data structure or object during a series of bits, so that it can be stored in the memory buffer or a file, or transmitted over a network link connected to a later or another computer in the same environment reconstruction.

Design an algorithm to serialization and de-serialization binary search tree. Serialization / de-serialization algorithm works is not limited. Just be sure binary search tree can be serialized to a string, and the string of anti-sequence can be reduced to the initial binary search tree.

Encoded string should be as compact as possible.

Note: Do not use class members / global / static variables to store state. Your serialization and de-serialization algorithm should be stateless.

	// Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        dfsSerialize(root,sb);
        return sb.toString();
    }


    public void dfsSerialize(TreeNode root,StringBuilder sb){
        if(root==null)
            return;
        sb.append(root.val).append(" ");
        dfsSerialize(root.left,sb);
        dfsSerialize(root.right,sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.length()==0)
            return null;
        String[] strs = data.split(" ");
        Queue<Integer> queue = new LinkedList<>();

        for(String str:strs){
            queue.offer(Integer.parseInt(str));
        }
        return dfsDeserialize(queue);
    }


    public TreeNode dfsDeserialize(Queue<Integer> q){
        if(q.isEmpty())
            return null;
        int cur =  q.poll();
        TreeNode root = new TreeNode(cur);
        Queue<Integer> sq = new LinkedList<>();
        while(!q.isEmpty() && q.peek()<cur){
            sq.offer(q.poll());
        }
        // 队列中比当前root节点小的节点用来构造左子数
        root.left = dfsDeserialize(sq);
        //比当前root大的用来构造root的右子数
        root.right = dfsDeserialize(q);
        return root;
    }
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/103767890