Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Serialize a binary tree

Convert a binary tree to a compact level-order string representation.

Python practice16 minTrees & Binary TreesIntermediateLast updated March 29, 2026

Problem statement

Implement serialize(root) that takes the root of a binary tree and returns a string encoding its structure and node values. Use level-order traversal (BFS). Represent missing children with the token 'null' and separate tokens with commas. Trim trailing 'null' tokens to keep the serialization compact. Return an empty string for an empty tree.

Task

Implement a serialize function that converts a binary tree to a string using level-order (BFS) with 'null' placeholders.

Examples

Example serialization

Input

build_tree_from_list([1,2,3,None,4,5])

Output

1,2,3,null,4,5

Level-order: 1,2,3,null,4,5,null,... Trim trailing nulls -> '1,2,3,null,4,5'.

Input format

A binary tree root (TreeNode) constructed via build_tree_from_list([...]).

Output format

A string with comma-separated node values and 'null' for missing children. Empty tree -> empty string.

Constraints

Nodes values are integers. Aim for O(n) time and O(n) space for the serialized string.

Samples

Sample 1

Input

build_tree_from_list([1,2,3,4,5,6,7])

Output

1,2,3,4,5,6,7

Perfect binary tree serializes without 'null's.