Serialize and Deserialize BST
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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
1 public class Codec { 2 public String serialize(TreeNode root) { 3 StringBuilder sb = new StringBuilder(); 4 serialize(root, sb); 5 return sb.toString(); 6 } 7 8 public void serialize(TreeNode root, StringBuilder sb) { 9 if (root == null) return; 10 sb.append(root.val).append(","); 11 serialize(root.left, sb); 12 serialize(root.right, sb); 13 } 14 15 // Decodes your encoded data to tree. 16 public TreeNode deserialize(String data) { 17 if (data.isEmpty()) return null; 18 int[] treeData = convertToIntArray(data.split(",")); 19 return deserialize(treeData, 0, treeData.length - 1); 20 } 21 22 public TreeNode deserialize(int[] treeData, int start, int end) { 23 if (start > end) return null; 24 if (start == end) return new TreeNode(treeData[start]); 25 26 TreeNode root = new TreeNode(treeData[start]); 27 int breakPoint = findBreakPoint(treeData, start + 1, end, treeData[start]); 28 root.left = deserialize(treeData, start + 1, breakPoint); 29 root.right = deserialize(treeData, breakPoint + 1, end); 30 return root; 31 } 32 33 private int findBreakPoint(int[] treeData, int start, int end, int target) { 34 for (int i = start; i <= end; i++) { 35 if (treeData[i] > target) { 36 return i - 1; 37 } 38 } 39 return end; 40 } 41 42 private int[] convertToIntArray(String[] input) { 43 int[] intArray = new int[input.length]; 44 for (int i = 0; i < input.length; i++) { 45 intArray[i] = Integer.parseInt(input[i]); 46 } 47 return intArray; 48 } 49 }