Fundamentals/Serializing and Deserializing Binary Tree
← PrevNext →
Implement serializeDFS(root, res) that serializes a binary tree by pre-order DFS into the array res. Push the current node's value when the node exists; push the sentinel "x" when the node is null. Recurse left, then right. The function mutates res in place and does not need to return a value.
Input
root: root node of a binary tree (may be null)
res: an array that will be appended to in place
Output
No return value. After the call, res contains the pre-order serialization with "x" markers for null children.
Examples
Example 1
Inputroot = [1, 2, 3]
res after call: [1, 2, "x", "x", 3, "x", "x"]
Example 2
Inputroot = [1]
res after call: [1, "x", "x"]
Constraints
Tree inputs use level-order arrays where null marks a missing child.
Use pre-order (node, left, right) traversal.