1. Level-Order BFS Serialization with Queue
Intuition
Queue BFS serializes every node or # for null. Deserializer uses a queue to attach children to each parent.
When to apply: When matching LeetCode's array format.
Algorithm
- Step 1: Serialize with BFS: append node.val or
#to string. - Step 2: Split string by comma.
- Step 3: Deserializer uses queue: pop parent, set left = nextToken, right = nextToken.
- Step 4: Return root.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Codec {public: string serialize(TreeNode* root) { if (!root) return "#"; string s = ""; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* cur = q.front(); q.pop(); if (!cur) s += "#,"; else { s += to_string(cur->val) + ","; q.push(cur->left); q.push(cur->right); } } return s; } TreeNode* deserialize(string data) { if (data == "#") return nullptr; stringstream ss(data); string item; getline(ss, item, ','); TreeNode* root = new TreeNode(stoi(item)); queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* cur = q.front(); q.pop(); if (getline(ss, item, ',')) { if (item != "#") { cur->left = new TreeNode(stoi(item)); q.push(cur->left); } } if (getline(ss, item, ',')) { if (item != "#") { cur->right = new TreeNode(stoi(item)); q.push(cur->right); } } } return root; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Linear serialization and queue deserialization. - Space complexity:
O(n)— String and queue hold O(n) elements.