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
- 48 lines of Java from the credited upstream file 449.java.
- The implementation visibly relies on sequence storage, 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.
1public class Codec {2 3 public String serialize(TreeNode root) {4 if (root == null)5 return "";6 StringBuilder sb = new StringBuilder();7 serialize(root, sb);8 return sb.toString();9 }10 11 12 public TreeNode deserialize(String data) {13 if (data.isEmpty())14 return null;15 16 final String[] vals = data.split(" ");17 Queue<Integer> q = new ArrayDeque<>();18 19 for (final String val : vals)20 q.offer(Integer.parseInt(val));21 22 return deserialize(Integer.MIN_VALUE, Integer.MAX_VALUE, q);23 }24 25 private void serialize(TreeNode root, StringBuilder sb) {26 if (root == null)27 return;28 sb.append(root.val).append(" ");29 serialize(root.left, sb);30 serialize(root.right, sb);31 }32 33 private TreeNode deserialize(int mn, int mx, Queue<Integer> q) {34 if (q.isEmpty())35 return null;36 37 final int val = q.peek();38 if (val < mn || val > mx)39 return null;40 41 q.poll();42 TreeNode root = new TreeNode(val);43 root.left = deserialize(mn, val, q);44 root.right = deserialize(val, mx, q);45 return root;46 }47}48