1. Preorder with Null Markers (General Tree Serialization)
Intuition
Traverse the tree in preorder. Append node values followed by a delimiter. For null children, append a special character such as #. Deserialization reads tokens sequentially from a queue: if token is #, return null; otherwise construct node and recurse for left and right children.
When to apply: When treating the BST as a general binary tree without taking advantage of the BST sorted property.
Algorithm
- Step 1 (Serialize): DFS preorder; if node is null, append
#,; else appendval,and recurse left, right. - Step 2 (Deserialize): Split string by commas into a token queue.
- Step 3: Define helper: pop token; if
#return null; else make TreeNode(token), recurse left and right.
#include <iostream>#include <string>#include <sstream>#include <queue>using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Codec {public: void serializeDfs(TreeNode* root, string& out) { if (!root) { out += "#,"; return; } out += to_string(root->val) + ","; serializeDfs(root->left, out); serializeDfs(root->right, out); } string serialize(TreeNode* root) { string out = ""; serializeDfs(root, out); return out; } TreeNode* deserializeDfs(queue<string>& q) { if (q.empty()) return nullptr; string token = q.front(); q.pop(); if (token == "#") return nullptr; TreeNode* node = new TreeNode(stoi(token)); node->left = deserializeDfs(q); node->right = deserializeDfs(q); return node; } TreeNode* deserialize(string data) { queue<string> q; stringstream ss(data); string token; while (getline(ss, token, ',')) { if (!token.empty()) q.push(token); } return deserializeDfs(q); }}; int main() { TreeNode* root = new TreeNode(2); root->left = new TreeNode(1); root->right = new TreeNode(3); Codec codec; string serialized = codec.serialize(root); cout << "Serialized: " << serialized << endl; TreeNode* res = codec.deserialize(serialized); cout << "Deserialized Root: " << res->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)