Serialize and Deserialize Binary Tree – Solution & Complexity
Solution Walkthrough
Step 1: Record null children explicitly
- A preorder traversal alone does not uniquely identify a binary tree, because you cannot tell where a subtree ends.
- Emitting a sentinel token like
#for everynullchild makes the preorder stream unambiguous: every node is followed immediately by its complete left subtree and then its complete right subtree.
Step 2: Deserialize with a shared token cursor
- Split the serialized string by
,and maintain a single cursor index. - Read the next token: if it is
#, returnNone; otherwise constructTreeNode(int(token)), recursively build.left, then recursively build.right.
- Split the serialized string by
Step 3: Optimal O(n) preorder codec
- Both
serializeanddeserializevisit every node and null pointer once:O(n)time andO(n)space.
- Both
Step 4: Common mistakes
- Treating node value
0as falsy (if (!val)) instead of checking for the#sentinel. - Calling
Array.shift()inside the deserialization loop, which turnsO(n)intoO(n^2); use an index pointer instead.
- Treating node value
Part of Blind 75 · NeetCode 150 · Grind 75