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.
publicclassCodec {
// Encodes a tree to a single string.public String serialize(TreeNode root) {
}
// Decodes your encoded data to tree.public TreeNode deserialize(String data) {
}
}
Use upper and lower boundaries to check whether we should add null.
To solve this problem, we will use Preorder Traversal for serialization. Preorder traversal processes the root node first, followed by the left subtree and then right subtree. This is ideal for reconstructing the binary search tree because we can split the values into left and right subtrees based on the BST property.
classSolution {
// Definition for a binary tree nodestaticclassTreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val= val;
}
}
// Serialize the BSTpublic String serialize(TreeNode root) {
StringBuilder sb =new StringBuilder();
serializeHelper(root, sb);
return sb.toString();
}
privatevoidserializeHelper(TreeNode node, StringBuilder sb) {
if (node ==null) return;
sb.append(node.val).append(','); // Append current node's value serializeHelper(node.left, sb); // Process left subtree serializeHelper(node.right, sb); // Process right subtree }
// Deserialize the BSTpublic TreeNode deserialize(String data) {
if (data.isEmpty()) returnnull;
String[] values = data.split(",");
return deserializeHelper(values, 0, values.length- 1, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode deserializeHelper(String[] values, int start, int end, int min, int max) {
if (start > end) returnnull;
int val = Integer.parseInt(values[start]);
if (val < min || val > max) returnnull; // Value out of range TreeNode root =new TreeNode(val);
int idx = start + 1;
while (idx <= end && Integer.parseInt(values[idx]) < val) idx++; // Split left and right subtrees root.left= deserializeHelper(values, start + 1, idx - 1, min, val); // Left subtree root.right= deserializeHelper(values, idx, end, val, max); // Right subtreereturn root;
}
}