449. Serialize and Deserialize BST

449. Serialize and Deserialize BST

Description

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.

Example 1:

1
2
Input: root = [2,1,3]
Output: [2,1,3]

Example 2:

1
2
Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • 0 <= Node.val <= 10^4
  • The input tree is guaranteed to be a binary search tree.

Hints/Notes

  • 2024/07/06
  • binary search tree
  • No solution from 0x3F

Solution

Language: C++

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
/**
* 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 {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) {
return "";
}
string res = to_string(root->val);
if (root->left) {
res += "," + serialize(root->left);
}
if (root->right) {
res += "," + serialize(root->right);
}
return res;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) {
return nullptr;
}
vector<int> nums;
int pos = 0;
while ((pos = data.find(",")) != string::npos) {
nums.push_back(stoi(data.substr(0, pos)));
data.erase(0, pos + 1);
}
nums.push_back(stoi(data));
return build(nums, 0, nums.size() - 1);
}

TreeNode* build(vector<int>& nums, int start, int end) {
if (start > end) {
return nullptr;
}
TreeNode* root = new TreeNode(nums[start]);
if (start == end) {
return root;
}
int i;
for (i = start; i <= end && nums[i] <= root->val; i++) {
}
root->left = build(nums, start + 1, i - 1);
root->right = build(nums, i, end);
return root;
}
};

// 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;