Topic describes
/ / 297. The serialization and deserialization of binary tree / / serialization is a data structure or object into a continuous bit operations, which can convert / / after the data is stored in a file or memory, at the same time can also be transferred over the network to another computer / / environment, take the opposite way to reconstruct the original data. // Please design an algorithm to implement binary tree serialization and deserialization. There is no limit to the logic of your sequential/unsequential // columnization algorithm, you just need to ensure that a binary tree can be serialized to a string and deserialize the string to the original tree structure. // Note: The input and output formats are the same as LeetCode currently uses. For details, see LeetCode's format for sequential // column binary trees. You don't have to go this way, you can solve the // problem in other ways.Copy the code
Answer key
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); // TreeNode ans = deser.deserialize(ser.serialize(root)); // Serialization function is very simple, the sequence traversal slightly changed, mainly difficult in deserialization function implementation, // deserialization function implementation difficult, known binary tree sequence traversal, rebuild binary tree. TreeNode // // : 23 ms, beating 49.31% of all Java commits 40.7 MB, Public class Codec {// Encodes a tree to a single string. Public string serialize(TreeNode) root) { if (root == null) return "[]"; StringBuilder sb = new StringBuilder(); sb.append("["); LinkedList<TreeNode> q = new LinkedList<>(); q.add(root); while (! q.isEmpty()) { TreeNode cur = q.removeFirst(); if (cur ! = null) { sb.append(cur.val + ","); q.add(cur.left); q.add(cur.right); } else { sb.append("null" + ","); } } sb.delete(sb.length() - 1, sb.length()); sb.append("]"); return sb.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.equals("[]")) return null; String indata = data.substring(1, data.length() - 1); String[] vals = indata.split(","); LinkedList<TreeNode> q = new LinkedList<>(); int i = 0; TreeNode head = new TreeNode(Integer.parseInt(vals[i++])); q.add(head); while (! q.isEmpty()) { TreeNode node = q.remove(); if (! vals[i].equals("null")) { node.left = new TreeNode(Integer.parseInt(vals[i])); q.add(node.left); } i++; if (! vals[i].equals("null")) { node.right = new TreeNode(Integer.parseInt(vals[i])); q.add(node.right); } i++; } return head; }}Copy the code