449. Serialize and Deserialize BST

LeetCode

Naive BFS Serialization with delimiters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private String serializeUtil(TreeNode root, String s){
if(root==null) s+="null,";
else{
s+=root.val+","+serializeUtil(root.left,s)+serializeUtil(root.right,s);
}
return s;
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return serializeUtil(root,"");
}

private TreeNode deserializeUtil(List<String> ls){
if(ls.get(0).equals("null")){
ls.remove(0);
return null;
}
TreeNode root=new TreeNode(Integer.valueOf(ls.get(0)));
ls.remove(0);
root.left=deserializeUtil(ls);
root.right=deserializeUtil(ls);
return root;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] dataArr=data.split(",");
List<String> dataList = new LinkedList<String>(Arrays.asList(dataArr));
return deserializeUtil(dataList);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

0%