Serialize and Deserialize Binary Tree

Preorder serialization with null markers; deserialize by recursively consuming the next token.

Hard
Time O(n) Space O(n)
LeetCode
4 min read
tree dfs design serialization

Problem#

Design an algorithm to serialize a binary tree into a string and deserialize it back.

Examples#

  • [1,2,3,null,null,4,5]"1,2,#,#,3,4,#,#,5,#,#" (preorder with null markers).
  • []"#".

Constraints#

  • The number of nodes is in [0, 10^4]. Values are in [-1000, 1000].

Approach#

Serialize via preorder traversal: emit value, then recurse on left and right; emit # for null. Deserialize: split on comma, consume tokens with a cursor — # returns null, otherwise create a node and recurse for left then right.

Solution#

Serialize and Deserialize Binary Tree
class Codec {
public:
string serialize(TreeNode* root) {
string s;
function<void(TreeNode*)> dfs = [&](TreeNode* u) {
if (!u) { s += "#,"; return; }
s += to_string(u->val) + ",";
dfs(u->left);
dfs(u->right);
};
dfs(root);
return s;
}
TreeNode* deserialize(string data) {
int i = 0;
function<TreeNode*()> build = [&]() -> TreeNode* {
int j = data.find(',', i);
string tok = data.substr(i, j - i);
i = j + 1;
if (tok == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(tok));
node->left = build();
node->right = build();
return node;
};
return build();
}
};

Editorial#

Preorder + null markers uniquely encodes the tree because every recursive call consumes exactly one token (either a node or a null marker). The cursor i is a shared state across recursive calls — equivalent to streaming the tokens.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.