Approach
Breadth-first search
For Serialize and Deserialize Binary Tree, 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
- 38 lines of Java from the credited upstream file 297-2.java.
- 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.
1public class Codec {2 3 public String serialize(TreeNode root) {4 StringBuilder sb = new StringBuilder();5 preorder(root, sb);6 return sb.toString();7 }8 9 10 public TreeNode deserialize(String data) {11 final String[] vals = data.split(" ");12 Queue<String> q = new ArrayDeque<>(List.of(vals));13 return preorder(q);14 }15 16 private void preorder(TreeNode root, StringBuilder sb) {17 if (root == null) {18 sb.append("n ");19 return;20 }21 22 sb.append(root.val).append(" ");23 preorder(root.left, sb);24 preorder(root.right, sb);25 }26 27 private TreeNode preorder(Queue<String> q) {28 final String s = q.poll();29 if (s.equals("n"))30 return null;31 32 TreeNode root = new TreeNode(Integer.parseInt(s));33 root.left = preorder(q);34 root.right = preorder(q);35 return root;36 }37}38