#297

Serialize and Deserialize Binary Tree

Hard Preorder with null markers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design an encoder that turns a binary tree into a string and a decoder that rebuilds the exact same tree from it.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: turn a tree into a string and back.

Why this works: preorder with "#" for null fully describes the shape; reading tokens back in the same order rebuilds it.

Example: 1 (2, 3 (4, 5))

"1,2,#,#,3,4,#,#,5,#,#"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the null markers, so different trees produce the same string.

Solve on LeetCode ↗
Complexity
  • Time: O(n) both ways.
  • Space: O(n).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon