/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
public List<String> list = new ArrayList<String>();
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return helper(root, "");
}
public String helper(TreeNode root, String s) {
if (root == null) {
s += "null,";
list.add("null");
} else {
s = s + root.val + ",";
list.add(String.valueOf(root.val));
helper(root.left, s);
helper(root.right, s);
}
return s;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return helpert();
}
public TreeNode helpert() {
if (list.get(0) == "null") {
list.remove(0);
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(list.get(0)));
list.remove(0);
root.left = helpert();
root.right = helpert();
return root;
}
}
// 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));
index out of bounds??
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
public String rserialize(TreeNode root, String str) {
// Recursive serialization.
if (root == null) {
str += "null,";
} else {
str += str.valueOf(root.val) + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return rserialize(root, "");
}
public TreeNode rdeserialize(List<String> l) {
// Recursive deserialization.
if (l.get(0).equals("null")) {
l.remove(0);
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(l.get(0)));
l.remove(0);
root.left = rdeserialize(l);
root.right = rdeserialize(l);
return root;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] data_array = data.split(",");
List<String> data_list = new LinkedList<String>(Arrays.asList(data_array));
return rdeserialize(data_list);
}
}
// 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));
Runtime: 484 ms, faster than 5.22% of Java online submissions for Serialize and Deserialize Binary Tree.
Memory Usage: 219.2 MB, less than 5.13% of Java online submissions for Serialize and Deserialize Binary Tree.
내거랑 비슷해보이는데.. 왜 안되는지 모를 ㅠㅠ