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.
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.
Example:
You may serialize the following tree:
1
/ \
2 3
/ \
4 5
as
"[1,2,3,null,null,4,5]"
Clarification:The above format is the same ashow LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Solution & Analysis
Depth-first Search
Pre-Oder Traversal:
The preorder DFS traverse follows recursively the order of root -> left subtree -> right subtree.
用一个辅助的queue,存入data.split(",")之后的元素,这样在构建树时,就可以按照相同的顺序:root -> left subtree -> right subtree
Complexity Analysis
Time complexity : in both serialization and deserialization functions, we visit each node exactly once, thus the time complexity is O(N), whereNNis the number of nodes, _i.e._the size of tree.
Space complexity : in both serialization and deserialization functions, we keep the entire tree, either at the beginning or at the end, therefore, the space complexity is O(N).
10 ms, faster than 92.02%
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassCodec {// Encodes a tree to a single string.publicStringserialize(TreeNode root) {if (root ==null) {return""; }StringBuilder sb =newStringBuilder();traverse(root, sb);// System.out.println(sb.toString());returnsb.toString(); }privatevoidtraverse(TreeNode root,StringBuilder sb) {if (root !=null) {sb.append(String.valueOf(root.val));sb.append(",");traverse(root.left, sb);traverse(root.right, sb); } else {sb.append("#");sb.append(","); } }// Decodes your encoded data to tree.publicTreeNodedeserialize(String data) {if (data ==null||data.isEmpty()) {returnnull; }String[] values =data.split(",");Queue<String> queue =newLinkedList<String>(Arrays.asList(values));returnbuildTree(queue); }privateTreeNodebuildTree(Queue<String> queue) {if (queue ==null||queue.isEmpty()) {returnnull; }String value =queue.poll();if (value.equals("#")) {returnnull; }TreeNode node =newTreeNode(Integer.parseInt(value));node.left=buildTree(queue);node.right=buildTree(queue);return node; }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
Concise Solution (serial part NOT RECOMMENDED)
via @cdai -- 以下:代码比较简洁,但是serial的部分不是很readable的地方在于,何时加delimiter ","
1,2,#,#,3,4,#,#,5,#,#
优点在保持了末尾不会有多余",", 但是逻辑上比较缠绕,一会pass by reference,一会返回值。因此尽管代码比较简洁,不推荐在面试中使用。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassCodec {publicStringserialize(TreeNode root) {returnserial(new StringBuilder(), root).toString(); }// Generate preorder stringprivateStringBuilderserial(StringBuilder str,TreeNode root) {if (root ==null) returnstr.append("#");str.append(root.val).append(",");serial(str,root.left).append(",");serial(str,root.right);return str; }publicTreeNodedeserialize(String data) {returndeserial(newLinkedList<>(Arrays.asList(data.split(",")))); }// Use queue to simplify position moveprivateTreeNodedeserial(Queue<String> q) {String val =q.poll();if ("#".equals(val)) returnnull;TreeNode root =newTreeNode(Integer.valueOf(val));root.left=deserial(q);root.right=deserial(q);return root; }}