Data Structures & Algorithms Master Level Finale
💡
Exercise 159

Serialize & Deserialize Tree 30 XP Hard

LeetCode Ctrl+Enter Run Ctrl+S Save

Design an algorithm to serialize a binary tree to a string and deserialize it back. The format must capture the structure completely including null nodes.

Preorder traversal with null markers. Serialize: DFS, write value or 'N' for null. Deserialize: read values, recursively build tree.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Serialize and deserialize a tree. Verify by printing the serialized string for tree [1,2,3,null,null,4,5].
Serialize: preorder DFS, join with commas, use 'N' for None. Deserialize: split, use an index to track position.
🧪 Test Cases
Input
s
Expected
1,2,N,N,3,4,N,N,5,N,N
Test case 1
Input
serialize(root2) == s
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.