Serialization converts a tree to a string; deserialization reconstructs it.
A common approach uses preorder with null markers:
def serialize(root):
if root == null:
return "null,"
return str(root.val) + "," + serialize(root.left) + serialize(root.right)
Result for tree : "1,2,null,null,3,null,null,"
Deserialization processes the string left to right:
def deserialize(data):
values = iter(data.split(","))
def build():
val = next(values)
if val == "null":
return null
node = TreeNode(int(val))
node.left = build()
node.right = build()
return node
return build()
The preorder sequence with null markers captures structure completely.