-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathSolution.java
77 lines (73 loc) · 2.27 KB
/
Solution.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* 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) {
List<TreeNode> list=new ArrayList<TreeNode>();
list.add(root);
StringBuffer sb=new StringBuffer();
while(list.size()!=0){
for(int i=0;i<list.size();i++){
TreeNode node=list.get(i);
if(node==null){
sb.append("null,");
}else{
sb.append(node.val);
sb.append(",");
list.add(node.left);
list.add(node.right);
}
list.remove(i);
i--;
}
}
String ans=sb.toString();
return ans.substring(0,sb.length()-1);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] strs=data.split(",");
if(strs[0].equals("null")){
return null;
}
TreeNode ans=new TreeNode(Integer.parseInt(strs[0]));
List<TreeNode> list=new ArrayList<TreeNode>();
list.add(ans);
int i=1;
while(i<strs.length){
List<TreeNode> sonList=new ArrayList<TreeNode>();
for(TreeNode node:list){
if(i>=strs.length){
return ans;
}
if(!strs[i].equals("null")){
TreeNode left=new TreeNode(Integer.parseInt(strs[i]));
node.left=left;
sonList.add(left);
}
i++;
if(i>=strs.length){
return ans;
}
if(!strs[i].equals("null")){
TreeNode right=new TreeNode(Integer.parseInt(strs[i]));
node.right=right;
sonList.add(right);
}
i++;
}
list=sonList;
}
return ans;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));