-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSerialize and Deserialize Binary Tree
53 lines (46 loc) · 1.47 KB
/
Serialize and Deserialize Binary Tree
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
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Codec {
public String serialize(TreeNode root) {
var bos = new ByteArrayOutputStream(1024 * 16);
serialize(root, bos);
return bos.toString(StandardCharsets.ISO_8859_1);
}
public TreeNode deserialize(String data) {
var bytes = data.getBytes(StandardCharsets.ISO_8859_1);
var bis = new ByteArrayInputStream(bytes);
return deserialize(bis);
}
static void serialize(TreeNode node, ByteArrayOutputStream bos) {
if (node == null) {
bos.write(0);
} else {
bos.write(1);
writeInt(bos, node.val);
serialize(node.left, bos);
serialize(node.right, bos);
}
}
static TreeNode deserialize(ByteArrayInputStream bis) {
if (bis.available() == 0 || bis.read() == 0) {
return null;
}
var n = new TreeNode(readInt(bis));
n.left = deserialize(bis);
n.right = deserialize(bis);
return n;
}
static void writeInt(ByteArrayOutputStream bos, int val) {
bos.write((val >>> 24) & 0xFF);
bos.write((val >>> 16) & 0xFF);
bos.write((val >>> 8) & 0xFF);
bos.write(val & 0xFF);
}
static int readInt(ByteArrayInputStream bis) {
int val = bis.read() << 24;
val |= bis.read() << 16;
val |= bis.read() << 8;
val |= bis.read();
return val;
}
}