序列化和反序列化二叉树 Serialize and Deserialize Binary Tree

问题:app

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.less

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.ui

For example, you may serialize the following treethis

    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.spa

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

解决:code

① 理论上说全部遍历的方法均可以。orm

可是为了使serialize和deserialize的过程都尽可能最简单,preorder是不错的选择。serialize的话,dfs比较好写,deserialize的话preorder和bfs比较好写。用“,”做为分隔符,“#”来表示null。例子里serialize以后结果就变成"1,2,3,#,#,4,5"。deserialize的时候用一个queue来保存string。leetcode

Time: O(N), Space: O(N)get

public class Codec { //25ms     // Encodes a tree to a single string.     public String serialize(TreeNode root) {         if (root == null) return "";         StringBuilder encodedStr = new StringBuilder();         encode(root,encodedStr);         return encodedStr.substring(1).toString();     }     public void encode(TreeNode root,StringBuilder sb){         if (root == null){             sb.append(",#");             return;         }         sb.append(",").append(root.val);         encode(root.left,sb);         encode(root.right,sb);     }     // Decodes your encoded data to tree.     public TreeNode deserialize(String data) {         if (data.length() == 0) return null;         Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));         return decode(queue);     }     public TreeNode decode(Queue<String> queue){         if (queue.isEmpty()) return null;         String cur = queue.poll();         if (cur.equals("#")) return null;         TreeNode root = new TreeNode(Integer.valueOf(cur));         root.left = decode(queue);         root.right = decode(queue);         return root;     } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));

相关文章
相关标签/搜索