[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;
    }
}
相关文章
相关标签/搜索