Serialization converts a tree to a string; deserialization reconstructs it.
A common approach uses preorder with null markers:
function serialize(root):
if root == null:
return "null,"
return toString(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:
function deserialize(data):
values = data.split(",")
i = 0
function build():
val = values[i]
i += 1
if val == "null":
return null
node = TreeNode(toInt(val))
node.left = build()
node.right = build()
return node
return build()
The preorder sequence with null markers captures structure completely.