cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 53 of 218
Ideas this builds on
Trees53 / 218

Serialize and restore a binary tree

Picture

Trees root-left and root-right can both visit values 1,2 but have different topology.

Predict

Why are null markers needed?

Walk through the small example

To preserve shape. Traversal order plus explicit missing-child markers uniquely describes topology.

Mental model and complete Python solution

Serialization writes both what exists and the meaningful gaps between nodes. Deserialization replays the same child-slot order; agreement on format is the whole contract.

What the function promises: Serialize integer-valued binary trees to a list containing integers or None, and deserialize that representation. Empty tree becomes an empty list.

from collections import deque

class TreeNode:
    def __init__(self, value):
        self.value, self.left, self.right = value, None, None

def serialize(root):
    if root is None: return []
    output, queue = [], deque([root])
    while queue:
        node = queue.popleft()
        if node is None: output.append(None)
        else:
            output.append(node.value); queue.extend((node.left,node.right))
    while output and output[-1] is None: output.pop()
    return output

def deserialize(values):
    if not values: return None
    root, queue, i = TreeNode(values[0]), deque(), 1
    queue.append(root)
    while queue and i < len(values):
        parent = queue.popleft()
        if values[i] is not None:
            parent.left = TreeNode(values[i]); queue.append(parent.left)
        i += 1
        if i < len(values) and values[i] is not None:
            parent.right = TreeNode(values[i]); queue.append(parent.right)
        i += 1
    return root

root = TreeNode(1); root.right = TreeNode(2); root.right.left = TreeNode(3)
assert serialize(root) == [1,None,2,3]
assert serialize(deserialize(serialize(root))) == [1,None,2,3]

Work and storage: O(n) time and O(n) output/queue space.

When to recognize it: Traversal order plus explicit missing-child markers uniquely describes topology.

Check before applying it: Delimiter-based text needs escaping; arbitrary values require a real encoding format.

Change one rule

Need a compact BST-only encoding.

See what changes

Preorder values can reconstruct using BST bounds when keys and duplicate policy are explicit; that shortcut does not work for arbitrary trees.

Connect

tree traversals: Traversal order is an encoding decision with a reconstruction contract.

queues: Level order assigns child slots parent by parent.