KatInterview

449. Serialize and Deserialize BST

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design an algorithm to serialize a Binary Search Tree (BST) into a string and deserialize that string back into the original BST. A key constraint is that the encoded string should be as compact as possible. This suggests we should leverage the properties of a BST to avoid storing redundant information, such as null pointers, which are often necessary for serializing a general binary tree.

Solution

Serialize and Deserialize BST in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

import collections
from typing import Optional

class Codec:

    def serialize(self, root: Optional[TreeNode]) -> str:
        """Encodes a tree to a single string.
        """
        vals = []
        
        # Helper to perform preorder traversal
        def preorder(node):
            if not node:
                return
            vals.append(str(node.val))
            preorder(node.left)
            preorder(node.right)
        
        preorder(root)
        return " ".join(vals)

    def deserialize(self, data: str) -> Optional[TreeNode]:
        """Decodes your encoded data to tree.
        """
        if not data:
            return None
        
        # Use a deque for efficient popping from the left
        vals = collections.deque(int(v) for v in data.split())
        
        # Helper to recursively build the tree
        def build(lower, upper):
            # If no values left or current value is out of bounds, end this path
            if not vals or not (lower < vals[0] < upper):
                return None
            
            # Current value is the root of this subtree
            val = vals.popleft()
            node = TreeNode(val)
            
            # Recursively build left and right subtrees with updated bounds
            node.left = build(lower, val)
            node.right = build(val, upper)
            return node
            
        return build(float('-inf'), float('inf'))

# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans

Serialize and Deserialize BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Codec {

    // Encodes a tree to a single string using preorder traversal.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        preorder(root, sb);
        // Remove the trailing space if any
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }

    // Helper for serialization
    private void preorder(TreeNode node, StringBuilder sb) {
        if (node == null) {
            return;
        }
        sb.append(node.val).append(" ");
        preorder(node.left, sb);
        preorder(node.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.isEmpty()) {
            return null;
        }
        Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(" ")));
        return build(queue, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    // Helper for deserialization: recursively builds the tree.
    private TreeNode build(Queue<String> queue, int lower, int upper) {
        // If queue is empty or the current value is out of bounds, this path is done.
        if (queue.isEmpty()) {
            return null;
        }
        int val = Integer.parseInt(queue.peek());
        if (val < lower || val > upper) {
            return null;
        }

        // The current value is the root of this subtree.
        queue.poll();
        TreeNode node = new TreeNode(val);
        
        // Recursively build left and right subtrees with updated bounds.
        node.left = build(queue, lower, val);
        node.right = build(queue, val, upper);

        return node;
    }
}

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

Serialize and Deserialize BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <sstream>
#include <string>
#include <queue>
#include <climits>

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        std::ostringstream out;
        preorder(root, out);
        std::string s = out.str();
        // Remove the trailing space if the string is not empty
        if (!s.empty()) {
            s.pop_back();
        }
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data.empty()) {
            return nullptr;
        }
        std::istringstream in(data);
        std::queue<int> q;
        int val;
        while (in >> val) {
            q.push(val);
        }
        // Use long for bounds to handle node values that are INT_MIN or INT_MAX.
        return build(q, LONG_MIN, LONG_MAX);
    }

private:
    // Helper for serialization: performs preorder traversal.
    void preorder(TreeNode* node, std::ostringstream& out) {
        if (!node) {
            return;
        }
        out << node->val << " ";
        preorder(node->left, out);
        preorder(node->right, out);
    }

    // Helper for deserialization: recursively builds the tree.
    TreeNode* build(std::queue<int>& q, long lower, long upper) {
        // If queue is empty or the current value is out of bounds, this path is done.
        if (q.empty() || q.front() < lower || q.front() > upper) {
            return nullptr;
        }

        // The current value is the root of this subtree.
        long val_long = q.front();
        q.pop();
        TreeNode* node = new TreeNode(static_cast<int>(val_long));

        // Recursively build left and right subtrees with updated bounds.
        node->left = build(q, lower, val_long);
        node->right = build(q, val_long, upper);

        return node;
    }
};

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

Serialize and Deserialize BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/*
 * Encodes a tree to a single string.
 */
function serialize(root: TreeNode | null): string {
    const values: number[] = [];

    // Helper function to perform preorder traversal.
    function preorder(node: TreeNode | null) {
        if (!node) {
            return;
        }
        values.push(node.val);
        preorder(node.left);
        preorder(node.right);
    }

    preorder(root);
    return values.join(' ');
};

/*
 * Decodes your encoded data to tree.
 */
function deserialize(data: string): TreeNode | null {
    if (!data) {
        return null;
    }

    // Use an array as a queue, shift() is like dequeue.
    const queue = data.split(' ').map(Number);

    // Helper function to recursively build the tree.
    function build(lower: number, upper: number): TreeNode | null {
        // If queue is empty or the current value is out of bounds, this path is done.
        if (queue.length === 0 || queue[0] < lower || queue[0] > upper) {
            return null;
        }

        // The current value is the root of this subtree.
        const val = queue.shift()!;
        const node = new TreeNode(val);

        // Recursively build left and right subtrees with updated bounds.
        node.left = build(lower, val);
        node.right = build(val, upper);

        return node;
    }

    return build(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY);
};


/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.