-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializeAndDeserializeBinaryTree.java
More file actions
69 lines (63 loc) · 1.93 KB
/
Copy pathSerializeAndDeserializeBinaryTree.java
File metadata and controls
69 lines (63 loc) · 1.93 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//time:o(n)
//space:o(n)
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
//corner case
if(root == null) return "";
//BFS-queue
Queue<TreeNode> q = new LinkedList<>();
StringBuilder s = new StringBuilder();
q.offer(root);
while(!q.isEmpty()){
TreeNode cur = q.poll();
if(cur == null) s.append("null");
else{
s.append(cur.val);
q.offer(cur.left);
q.offer(cur.right);
}
s.append(",");
}
s.deleteCharAt(s.length()-1);
return s.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
//corner case
if(data == "") return null;
//split string by ","
String [] s = data.split(",");
//queue,not empty
Queue<TreeNode> q = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
q.offer(root);
//1.create treenode;2.connect to parent node;3.add to queue
for(int i = 1; i < s.length; i++){
TreeNode parent = q.poll();
if(!s[i].equals("null")){
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
parent.left = left;
q.offer(left);
}
if(!s[++i].equals("null")){
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
parent.right = right;
q.offer(right);
}
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));