-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serialize and deserialize BST
35 lines (30 loc) · 1.01 KB
/
Serialize and deserialize BST
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
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null) return "#/";
return root.val+"/"+serialize(root.left)+serialize(root.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("#")) return null;
int[] t={0};
String[] arr=data.split("/");
return helper(arr, t);
}
TreeNode helper(String[] arr, int[] t){
if(arr[t[0]].equals("#")) return null;
TreeNode root=new TreeNode(Integer.parseInt(arr[t[0]]));
t[0]=t[0]+1;
root.left=helper(arr, t);
t[0]=t[0]+1;
root.right=helper(arr, t);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;
#Status: encountered such question for first time, took a long time