Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.
An example of testdata: Binary tree {3,9,20,#,#,15,7}
, denote the following structure:
3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.
分析:
利用preorder + full tree的性质, 我们可以把bt还原。对于一个full tree, 当我们用recursion 还原完成左边部分后,剩余部分永远是属于右边部分的。
1 public String serialize(TreeNode root) { 2 if (root == null) return null; 3 4 Stack<TreeNode> stack = new Stack<TreeNode>(); 5 stack.push(root); 6 StringBuilder sb = new StringBuilder(); 7 8 while (!stack.isEmpty()) { 9 TreeNode node = stack.pop(); 10 if (node != null) { 11 sb.append(node.val + ","); 12 stack.push(node.right); 13 stack.push(node.left); 14 } else { 15 sb.append("#,"); 16 } 17 } 18 19 return sb.toString().substring(0, sb.length() - 1); 20 } 21 22 // Decodes your encoded data to tree. 23 public TreeNode deserialize(String data) { 24 if (data == null) return null; 25 26 int[] idx = { 0 }; 27 String[] arr = data.split(","); 28 return helper(arr, idx); 29 } 30 31 public TreeNode helper(String[] arr, int[] idx) { 32 if (arr[idx[0]].equals("#")) return null; 33 TreeNode root = new TreeNode(Integer.parseInt(arr[idx[0]])); 34 35 idx[0]++; 36 root.left = helper(arr, idx); 37 idx[0]++; 38 root.right = helper(arr, idx); 39 40 return root; 41 }
Approach 2:
1 public class Codec { 2 private static final String spliter = ","; 3 private static final String NN = "X"; 4 5 // Encodes a tree to a single string. 6 public String serialize(TreeNode root) { 7 StringBuilder sb = new StringBuilder(); 8 buildString(root, sb); 9 return sb.toString(); 10 } 11 12 private void buildString(TreeNode node, StringBuilder sb) { 13 if (node == null) { 14 sb.append(NN).append(spliter); 15 } else { 16 sb.append(node.val).append(spliter); 17 buildString(node.left, sb); 18 buildString(node.right,sb); 19 } 20 } 21 // Decodes your encoded data to tree. 22 public TreeNode deserialize(String data) { 23 Deque<String> nodes = new LinkedList<>(); 24 nodes.addAll(Arrays.asList(data.split(spliter))); 25 return buildTree(nodes); 26 } 27 28 private TreeNode buildTree(Deque<String> nodes) { 29 String val = nodes.remove(); 30 if (val.equals(NN)) return null; 31 else { 32 TreeNode node = new TreeNode(Integer.valueOf(val)); 33 node.left = buildTree(nodes); 34 node.right = buildTree(nodes); 35 return node; 36 } 37 } 38 }