-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize binary tree
More file actions
52 lines (47 loc) · 1.27 KB
/
serialize binary tree
File metadata and controls
52 lines (47 loc) · 1.27 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
package codec;
/**
*
* @author junye.mao
*/
public class Codec {
public String serialize(TreeNode root) { //用StringBuilder
StringBuilder res = ser_help(root, new StringBuilder());
return res.toString();
}
public StringBuilder ser_help(TreeNode root, StringBuilder str){
if(null == root){
str.append("null,");
return str;
}
str.append(root.val);
str.append(",");
str = ser_help(root.left, str);
str = ser_help(root.right, str);
return str;
}
public TreeNode deserialize(String data) {
String[] str_word = data.split(",");
List<String> list_word = new LinkedList<String>(Arrays.asList(str_word));
return deser_help(list_word);
}
public TreeNode deser_help(List<String> li){
if(li.get(0).equals("null")){
li.remove(0);
return null;
}
TreeNode res = new TreeNode(Integer.valueOf(li.get(0)));
li.remove(0);
res.left = deser_help(li);
res.right = deser_help(li);
return res;
}
}