Approach
Breadth-first search
For Serialize and Deserialize BST, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 50 lines of C++ from the credited upstream file 449.cpp.
- The implementation visibly relies on work queue.
- 1 loop block detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Codec {2 public:3 4 string serialize(TreeNode* root) {5 if (root == nullptr)6 return "";7 string s;8 serialize(root, s);9 return s;10 }11 12 13 TreeNode* deserialize(string data) {14 if (data.empty())15 return nullptr;16 17 istringstream iss(data);18 queue<int> q;19 20 for (string s; iss >> s;)21 q.push(stoi(s));22 23 return deserialize(INT_MIN, INT_MAX, q);24 }25 26 private:27 void serialize(TreeNode* root, string& s) {28 if (root == nullptr)29 return;30 s += to_string(root->val) + " ";31 serialize(root->left, s);32 serialize(root->right, s);33 }34 35 TreeNode* deserialize(int mn, int mx, queue<int>& q) {36 if (q.empty())37 return nullptr;38 39 const int val = q.front();40 if (val < mn || val > mx)41 return nullptr;42 43 q.pop();44 TreeNode* root = new TreeNode(val);45 root->left = deserialize(mn, val, q);46 root->right = deserialize(val, mx, q);47 return root;48 }49};50