[LeetCode] Serialize and Deserialize BST

449. Serialize and Deserialize BST

Serialization is 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 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.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
void sHelper(TreeNode* node, string& res) {
if(!node) res += "#,";
else {
res += to_string(node->val) + ',';
sHelper(node->left, res);
sHelper(node->right, res);
}
}
int parseNum(string& s, int& p) {
int res = 0;
while(p < s.length() and isdigit(s[p])) {
res = res * 10 + (s[p++] & 0b1111);
}
p++;
return res;
}
TreeNode* dHelper(string& d, int& i) {
if(i >= d.length() or d[i] == '#') {
i += 2; return NULL;
}

TreeNode* node = new TreeNode(parseNum(d,i));
node->left = dHelper(d,i);
node->right = dHelper(d,i);

return node;
}
public:

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res = "";
sHelper(root, res);
return res;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int p = 0;
return dHelper(data, p);
}
};

// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/14/PS/LeetCode/serialize-and-deserialize-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.