Because preorder traversal follows a fixed root-left-right order, and null markers preserve missing children. Using the same order during deserialization allows us to reconstruct the exact original tree unambiguously.
1
/ \
2 3
I visit 1 first, then 2.
Node 2 has no left or right child, so I write two null markers.
Then recursion returns to node 1 and visits node 3.
Node 3 also has two null children.
Time is O(n), because every node is processed once.
Space is O(n) for the serialized output. The recursion stack is O(h), where h is the tree height, and in the worst case h can be n.
I read characters until the delimiter. If I see a minus sign first, I store the sign separately, parse the digits into an integer, then apply the sign.