LeetCode 449: Serialize and Deserialize BST Solution

Master LeetCode problem 449 (Serialize and Deserialize BST), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To serialize and deserialize a binary search tree (BST), we can perform an in-order traversal to serialize the BST into a string. During deserialization, we can reconstruct the BST using the in-order traversal string. We will use recursion for both serialization and deserialization.

  1. During Serialization:

    • Perform an in-order traversal of the BST.
    • Append each node's value followed by a delimiter to the serialized string.
  2. During Deserialization:

    • Split the input string to extract the values of the nodes.
    • Recursively build the BST using the extracted values.

Solution Code

public class Codec {

    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serializeHelper(root, sb);
        return sb.toString();
    }

    private void serializeHelper(TreeNode root, StringBuilder sb) {
        if (root == null) {
            return;
        }
        serializeHelper(root.left, sb);
        sb.append(root.val).append(",");
        serializeHelper(root.right, sb);
    }

    public TreeNode deserialize(String data) {
        String[] values = data.split(",");
        return deserializeHelper(values, 0, values.length - 1);
    }

    private TreeNode deserializeHelper(String[] values, int start, int end) {
        if (start > end) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(values[start]));
        int index;
        for (index = start; index <= end; index++) {
            if (Integer.parseInt(values[index]) > node.val) {
                break;
            }
        }
        node.left = deserializeHelper(values, start + 1, index - 1);
        node.right = deserializeHelper(values, index, end);
        return node;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 449 (Serialize and Deserialize BST)?

This page provides optimized solutions for LeetCode problem 449 (Serialize and Deserialize BST) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 449 (Serialize and Deserialize BST)?

The time complexity for LeetCode 449 (Serialize and Deserialize BST) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 449 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 449 in Java, C++, or Python.

Back to LeetCode Solutions