LeetCode-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.
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.
For example, you may serialize the following tree
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.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Analysis:
While using bfs is intuitive, we can use dfs also.
Solution:
1 /** 2 * Definition for a binary tree node. public class TreeNode { int val; TreeNode 3 * left; TreeNode right; TreeNode(int x) { val = x; } } 4 */ 5 public class Codec { 6 7 // Encodes a tree to a single string. 8 public String serialize(TreeNode root) { 9 StringBuilder builder = new StringBuilder(); 10 serializeRecur(root,builder); 11 return builder.toString(); 12 } 13 14 public void serializeRecur(TreeNode cur, StringBuilder builder) { 15 if (cur == null) { 16 builder.append("n"); 17 return; 18 } 19 builder.append(cur.val); 20 builder.append(" "); 21 serializeRecur(cur.left,builder); 22 builder.append(" "); 23 serializeRecur(cur.right,builder); 24 } 25 26 int cur = -1; 27 28 // Decodes your encoded data to tree. 29 public TreeNode deserialize(String data) { 30 cur = -1; 31 String[] nodes = data.split(" "); 32 return deseriazlieRecur(nodes); 33 34 } 35 36 public TreeNode deseriazlieRecur(String[] nodes) { 37 cur++; 38 if (nodes[cur].equals("n")) { 39 return null; 40 } 41 42 TreeNode curNode = new TreeNode(Integer.parseInt(nodes[cur])); 43 curNode.left = deseriazlieRecur(nodes); 44 curNode.right = deseriazlieRecur(nodes); 45 return curNode; 46 } 47 48 } 49 50 // Your Codec object will be instantiated and called as such: 51 // Codec codec = new Codec(); 52 // codec.deserialize(codec.serialize(root));