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
- 42 lines of Python from the credited upstream file 449.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks 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 def serialize(self, root: TreeNode | None) -> str:3 """Encodes a tree to a single string."""4 if not root:5 return ''6 chars = []7 self._serialize(root, chars)8 return ''.join(chars)9 10 def deserialize(self, data: str) -> TreeNode | None:11 """Decodes your encoded data to tree."""12 if not data:13 return None14 q = collections.deque(int(val) for val in data.split())15 return self._deserialize(-math.inf, math.inf, q)16 17 def _serialize(self, root: TreeNode | None, chars: list[str]) -> None:18 if not root:19 return20 chars.append(str(root.val))21 chars.append(' ')22 self._serialize(root.left, chars)23 self._serialize(root.right, chars)24 25 def _deserialize(26 self,27 mn: int,28 mx: int,29 q: collections.deque[int]30 ) -> TreeNode | None:31 if not q:32 return None33 34 val = q[0]35 if val < mn or val > mx:36 return None37 38 q.popleft()39 return TreeNode(val,40 self._deserialize(mn, val, q),41 self._deserialize(val, mx, q))42