Explain tree serialization.
Skip to solutionKEEP THE
hardDSA
How do you serialize and deserialize a binary tree?
870 views
01
Understand the problem
treesserialization
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Do a preorder traversal emitting node values and a sentinel (e.g. #) for nulls into a string. To deserialize, consume tokens in the same preorder, building nodes and stopping branches at sentinels. Both are O(n). BFS/level-order encoding works too.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Preorder serialize/deserialize
Run Playgroundclass TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def serialize(root):
out = []
def dfs(node):
if not node:
out.append('#')
return
out.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(out)
def deserialize(data):
tokens = iter(data.split(','))
def build():
val = next(tokens)
if val == '#':
return None
node = TreeNode(int(val))
node.left = build()
node.right = build()
return node
return build()
# --- demo ---
root = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
data = serialize(root)
print(data) # 1,2,#,#,3,4,#,#,5,#,#
print(serialize(deserialize(data))) # same string -> round-trip ok05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 107 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.