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 TreeSerialization 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
- 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.
- Join the values into a single string, typically comma-separated.
- To deserialize: split the string back into tokens and process them in the same pre-order order.
- 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
- Pre-order with nulls: 1, 2, #, #, 3, 4, #, #, 5, #, #
- 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
Press βΆ Run to watch it step by step.
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: serializeBehind 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
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
Ready for the next step?
See the same ideas in action β visualize the algorithms that operate on these structures, or take a guided course.