Skip to main content

Serialize and Deserialize Binary Tree

Convert a binary tree to a string.

Serialize and Deserialize forces you to pick a format that survives a round trip, and pre-order with null markers is the cleanest pick. The deserialize side is the real test: a shared cursor over your tokens rebuilds the tree in one pass. Get this and you understand why null placeholders are not optional, they are the structure.

Examples

You write

serialize(root: Optional[TreeNode])

deserialize(data: str)

  1. Example 1

    Input
    [1,2,3,null,null,4,5]
    returns
    [1,2,3,null,null,4,5]
  2. Example 2

    Input
    []
    returns
    []

The pattern behind it

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Design

I reach for it when

  • The statement describes a class with methods, not one function.
  • Each method needs to be fast, and the structure decides how fast.

Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.

All 27 Design problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Serialize and Deserialize Binary Treehard

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.