-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerilalize.java
More file actions
44 lines (42 loc) · 1.1 KB
/
Serilalize.java
File metadata and controls
44 lines (42 loc) · 1.1 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
public class Solution {
public int index = -1; // 节点在序列中的索引
/**
* 序列化
* 前序遍历,将二叉树节点的值转为字符序列,null转为“#”
*
* @param root
* @return
*/
String Serialize(TreeNode root) {
StringBuffer s = new StringBuffer();
if (root == null) {
s.append("#,");
return s.toString();
}
s.append(root.val + ",");
s.append(Serialize(root.left));
s.append(Serialize(root.right));
return s.toString();
}
/**
* 反序列化
*
* @param str
* @return
*/
TreeNode Deserialize(String str) {
index++;
int length = str.length();
if (index >= length) {
return null;
}
String[] nodeSeq = str.split(",");
TreeNode pNode = null;
if (!nodeSeq[index].equals("#")) {
pNode = new TreeNode(Integer.valueOf(nodeSeq[index]));
pNode.left = Deserialize(str);
pNode.right = Deserialize(str);
}
return pNode;
}
}