设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7}
,表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
注意事项
对二进制树进行反序列化或序列化的方式没有限制,LintCode将您的serialize
输出作为deserialize
的输入,它不会检查序列化的结果。
解题思路1:
首先,老规矩,看到二叉树,想到二叉树的三种遍历方式。
然后,这里需要序列化和反序列化二叉树,可以采用的方法很多了。多种遍历方式都可以,只有在序列化和反序列化时采用相同的遍历方式即可。其中较为简单的是深度遍历和层次遍历。
思路1采用深度遍历,这种方法也比较容易理解和实现。
-
序列化,即将二叉树转成字符串。因为二叉树中包含
null
节点。需要采用一个特殊字符标记,因为这里的二叉树的值都是数字,所以可以采用非数字作为标记,如采用#
。每个节点间用,
分割。然后就是按照前序遍历的方法,输入二叉树成字符串,较为简单,不再赘述。 -
反序列化,即将刚才生成的字符串转换成二叉树。首先,将字符串按照
,
split成字符串数组的形式,该数组中每一个元素即为一个二叉树的节点。
这里可以很简单的用一个全局变量curr记录,当前遍历的数组index,剩下的就是按照前序遍历的方式重建二叉树。/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ public String serialize(TreeNode root) { // write your code here StringBuilder sb = new StringBuilder(); dfs(root, sb); return sb.toString(); } private void dfs(TreeNode root, StringBuilder sb){ if(root == null){ sb.append("#,"); return; } sb.append(root.val+","); dfs(root.left, sb); dfs(root.right, sb); } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ public TreeNode deserialize(String data) { // write your code here String[] strs = data.split(","); return helper(strs); } private int cur = 0; private TreeNode helper(String[] strs){ if(cur < 0 || cur >= strs.length) return null; String word = strs[cur++]; if(word.equals("#")) return null; TreeNode root = new TreeNode(Integer.valueOf(word)); root.left = helper(strs); root.right = helper(strs); return root; } }