请实现两个函数,分别用来序列化和反序列化二叉树。
你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null){
return "[]";
}
StringBuilder res = new StringBuilder();
res.append("[");
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while( !queue.isEmpty() ){
TreeNode temp = queue.poll();
if(temp != null){
res.append(temp.val + ",");
queue.add(temp.left);
queue.add(temp.right);
}else{
res.append("null,");
}
}
res.deleteCharAt(res.length()-1);
res.append("]");
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("[]")){
return null;
}
String[] vals = data.substring(1,data.length()-1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while( !queue.isEmpty() ){
TreeNode temp = queue.poll();
if( !vals[i].equals("null") ){
temp.left = new TreeNode(Integer.parseInt(vals[i]));
queue.add(temp.left);
}++i;
if( !vals[i].equals("null") ){
temp.right = new TreeNode(Integer.parseInt(vals[i]));
queue.add(temp.right);
}++i;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
执行用时:19 ms, 在所有 Java 提交中击败了55.68%的用户
内存消耗:43.7 MB, 在所有 Java 提交中击败了48.64%的用户
通过测试用例:48 / 48