Data Structures Β· Visualization

Binary Tree: Serialize & Deserialize

Binary Tree

Serialization converts a binary tree into a string (or array) that fully captures its shape and values, so it can be stored or transmitted; deserialization rebuilds the exact same tree from that string. Time: O(n) for both serialize and deserialize. Space: O(n) for the string plus O(h) recursion stack.

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Serialize & Deserialize

Binary Tree

Serialization converts a binary tree into a string (or array) that fully captures its shape and values, so it can be stored or transmitted; deserialization rebuilds the exact same tree from that string. A common approach uses pre-order traversal with explicit null markers.

How Serialize & Deserialize Works

  1. To serialize: perform a pre-order traversal (root, left, right), writing each node's value, and writing a sentinel (e.g. '#') whenever a child is null.
  2. Join the values into a single string, typically comma-separated.
  3. To deserialize: split the string back into tokens and process them in the same pre-order order.
  4. Recursively build each node: if the next token is the null sentinel, return null; otherwise create a node and recursively fill its left, then right, children.

Serialize & Deserialize Worked Example

Input: Serialize tree with root 1, left child 2 (leaf), right child 3 with children 4 and 5

  1. Pre-order with nulls: 1, 2, #, #, 3, 4, #, #, 5, #, #
  2. Deserializing reads tokens in the same order, rebuilding node 1, then 2 with two null children, then 3 with children 4 and 5

Output: The reconstructed tree is structurally identical to the original

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children β€” usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press β–Ά Run to watch it step by step.
Python Β· Binary Trees in Code
def serialize(root):
    out = []
    def dfs(n):
        if not n:
            out.append('null')
            return
        out.append(str(n.val))      # pre-order
        dfs(n.left)
        dfs(n.right)
    dfs(root)
    return ','.join(out)

def deserialize(s):
    it = iter(s.split(','))
    def build():
        v = next(it)
        if v == 'null':
            return None
        n = Node(int(v))
        n.left = build()
        n.right = build()
        return n
    return build()
# example: serialize
Input: Serialize tree with root 1, left child 2 (leaf), right child 3 with children 4 and 5

Behind the Scenes Execution

Press β–Ά Run in the visualizer β€” the call stack, registers and memory will replay here in sync with the code, line by line.

Serialize & Deserialize Time & Space Complexity

TimeO(n) for both serialize and deserialize
SpaceO(n) for the string plus O(h) recursion stack

When to Use Serialize & Deserialize

  • Saving/loading tree-shaped data to disk or a database
  • Sending tree structures over a network API
  • Deep-copying a tree

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired β€” free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action β€” visualize the algorithms that operate on these structures, or take a guided course.