[LeetCode] Problem 449 - Serialize and Deserialize BST

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note

Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
preorder(root, sb);
return sb.length() < 1 ? "" : sb.deleteCharAt(sb.length() - 1).toString();
}

public TreeNode deserialize(String data) {
if (data.length() < 1)
return null;

String[] str = data.split(" ");
return construct(str, 0, str.length - 1);
}

private void preorder(TreeNode root, StringBuilder sb) {
if (root == null)
return;

sb.append(root.val + " ");

preorder(root.left, sb);
preorder(root.right, sb);
}

private TreeNode construct(String[] str, int start, int end) {
if (start > end)
return null;

TreeNode root = new TreeNode(Integer.parseInt(str[start]));

int i = start + 1;

for (; i <= end; i++) {
if (Integer.parseInt(str[i]) > root.val)
break;
}

root.left = construct(str, start + 1, i - 1);
root.right = construct(str, i, end);
return root;
}