-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path449.java
More file actions
91 lines (83 loc) · 2.63 KB
/
449.java
File metadata and controls
91 lines (83 loc) · 2.63 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private TreeNode root=null;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
this.root=root;
return "";
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
__________________________________________________________________________________________________
sample 36992 kb submission
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "#";
}
StringBuilder sb = new StringBuilder();
Queue<TreeNode> qu = new LinkedList<>();
qu.offer(root);
while (!qu.isEmpty()) {
TreeNode cur = qu.poll();
if (cur == null) {
sb.append("#");
} else {
sb.append(cur.val);
qu.offer(cur.left);
qu.offer(cur.right);
}
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
data = data.trim();
if (data.equals("#")) {
return null;
}
String[] nodeVal = data.split("\\s+");
Deque<TreeNode> qu = new ArrayDeque<>();
TreeNode head = new TreeNode(Integer.parseInt(nodeVal[0]));
qu.offer(head);
int idx = 1;
while (idx < nodeVal.length) {
TreeNode cur = qu.poll();
if (nodeVal[idx].equals("#")) {
cur.left = null;
idx++;
} else {
cur.left = new TreeNode(Integer.parseInt(nodeVal[idx++]));
qu.offer(cur.left);
}
if (nodeVal[idx].equals("#")) {
cur.right = null;
idx++;
} else {
cur.right = new TreeNode(Integer.parseInt(nodeVal[idx++]));
qu.offer(cur.right);
}
}
return head;
}
}
__________________________________________________________________________________________________