[LeetCode]Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

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 across a network connection link to be reconstructed later in the same or another computer environment.html

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.node

For example, you may serialize the following treeapp

1
  / \
 2   3
    / \
   4   5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.less

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.ui

分析

相似於Tree的serialization最簡單的方法仍是依照某種遍歷順序用recursion來serialize。而由於deserialization來講preorder最方便,由於root很好找,老是第一個,因此咱們優先選用preorder的遍歷順序完成serialization及deserialization。this

關於deserialization, 咱們能夠用一個queue來存serialization的結果,每次deserialize的時候依次從queue中讀取值來建node, 因爲對null的node也serialize, 因此只要依照preorder的順序deserialize, 不用擔憂queue中的node值與實際node不匹配。spa

這道題Follow up能夠是N-ary Tree的serialization及deserialization, 或者相似html, xml的serializationrest

方法仍是同樣,依照某種遍歷順序用recursion來作。code

複雜度

Serialization

time: O(n), space: O(1)orm

Deserialization

time: O(n), space: O(n)

代碼

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null)
            return "null";
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        String left = serialize(root.left);
        String right = serialize(root.right);
        sb.append(", "); // 用符號分開不一樣node值,方便deserialization
        sb.append(left);
        sb.append(", ");
        sb.append(right);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        
        // 把全部node依照preorder serialize後的結果依次存入queue中
        Queue<String> q = new LinkedList<>();
        String[] strs = data.split(", ");
        for (String s : strs) {
            q.add(s);
        }
        return helper(q);
    }
    
    // 從queue中依次取值建node, 順序爲preorder
    public TreeNode helper(Queue<String> q) {
        String s = q.remove();
        if (s.equals("null"))
            return null;
        TreeNode root = new TreeNode(Integer.parseInt(s));
        root.left = helper(q);
        root.right = helper(q);
        return root;
    }
}
相關文章
相關標籤/搜索