Skip to content

Serialize and Deserialize Binary Tree⚓︎

Link

Description⚓︎

Serialization is the process of 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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Example 1:

Example

  • Input: root = [1,2,3,null,null,4,5]
  • Output: [1,2,3,null,null,4,5]

Example 2:

  • Input: root = []
  • Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • -1000 <= Node.val <= 1000

Solution⚓︎

Pre-order Traversal⚓︎

/**
 * 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 {
private:
    void _serialize(TreeNode* root, ostringstream& out) {
        if (root) {
            out << root->val << ' ';
            _serialize(root->left, out);
            _serialize(root->right, out);
        } else {
            out << "# ";
        }
    }

    TreeNode* _deserialize(istringstream& in) {
        string val;
        in >> val;
        if (val == "#") return nullptr;
        TreeNode* root = new TreeNode(stoi(val));
        root->left = _deserialize(in);
        root->right = _deserialize(in);
        return root;
    }

public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        _serialize(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return _deserialize(in);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));

Note: In-order Traversal cannot be serialized or deserialized.

Level-order Traversal⚓︎

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

        ostringstream out;
        queue<TreeNode*> que;
        que.push(root);

        while (!que.empty()) {
            TreeNode* node = que.front();
            que.pop();

            if (node) {
                out << node->val << " ";
                que.push(node->left);
                que.push(node->right);
            } else {
                out << "# ";
            }
        }

        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data.empty()) return nullptr;

        istringstream in(data);
        string val;
        getline(in, val, ' ');

        TreeNode* root = new TreeNode(stoi(val));
        queue<TreeNode*> que;
        que.push(root);

        while (!que.empty()) {
            TreeNode* node = que.front();
            que.pop();

            if (!getline(in, val, ' ')) break;
            if (val != "#") {
                TreeNode* leftChild = new TreeNode(stoi(val));
                node->left = leftChild;
                que.push(leftChild);
            }

            if (!getline(in, val, ' ')) break;
            if (val != "#") {
                TreeNode* rightChild = new TreeNode(stoi(val));
                node->right = rightChild;
                que.push(rightChild);
            }
        }

        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
  • Time complexity: \(O(N)\);
  • Space complexity: \(O(N)\).