Algo-Sim › Binary Trees & BST

Serialize and Deserialize Binary Tree

Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Write the tree in preorder with "#" for null children, then read the tokens back in the same order to rebuild it.

Problem

Design two functions: serialize turns a binary tree into a string, and deserialize turns that string back into an identical tree. Any format works as long as the round trip is exact.

Constraints

Edge cases to test

Follow-up questions

Why mark nulls?
Preorder alone is ambiguous; with null markers each token sequence describes exactly one tree.
What changes for a BST?
No null markers are needed: preorder plus the BST bounds rebuilds it in O(n) (LC 449).

Solution

Java

public class Codec {
    public String serialize(TreeNode root) {
        List<String> out = new ArrayList<>();
        write(root, out);
        return String.join(",", out);
    }

    private void write(TreeNode node, List<String> out) {
        if (node == null) { out.add("#"); return; }
        out.add(String.valueOf(node.val));
        write(node.left, out);
        write(node.right, out);
    }

    public TreeNode deserialize(String data) {
        Deque<String> tokens = new ArrayDeque<>(Arrays.asList(data.split(",")));
        return read(tokens);
    }

    private TreeNode read(Deque<String> tokens) {
        String t = tokens.poll();
        if (t.equals("#")) return null;
        TreeNode node = new TreeNode(Integer.parseInt(t));
        node.left = read(tokens);
        node.right = read(tokens);
        return node;
    }
}

Python

class Codec:
    def serialize(self, root):
        out = []

        def write(node):
            if not node:
                out.append("#")
                return
            out.append(str(node.val))
            write(node.left)
            write(node.right)

        write(root)
        return ",".join(out)

    def deserialize(self, data):
        tokens = iter(data.split(","))

        def read():
            t = next(tokens)
            if t == "#":
                return None
            node = TreeNode(int(t))
            node.left = read()
            node.right = read()
            return node

        return read()

C++

#include <bits/stdc++.h>
using namespace std;

class Codec {
  public:
    string serialize(TreeNode *root) {
        vector<string> out = {};
        write(root, out);
        string result;
        for (const auto &token : out) {
            if (!result.empty())
                result += ',';
            result += token;
        }
        return result;
    }

    void write(TreeNode *node, vector<string> &out) {
        if (node == nullptr) {
            out.push_back("#");
            return;
        }
        out.push_back(to_string(node->val));
        write(node->left, out);
        write(node->right, out);
    }

    TreeNode *deserialize(string &data) {
        deque<string> tokens;
        string token;
        istringstream stream(data);
        while (getline(stream, token, ','))
            tokens.push_back(token);
        return read(tokens);
    }

    TreeNode *read(deque<string> &tokens) {
        string t = tokens.front();
        tokens.pop_front();
        if ((t == "#"))
            return nullptr;
        TreeNode *node = new TreeNode(stoi(t));
        node->left = read(tokens);
        node->right = read(tokens);
        return node;
    }
};

More Binary Trees & BST problems