297. Serialize and Deserialize Binary Tree
You may serialize the following tree:
1
/ \
2 3
/ \
4 5
as "[1,2,3,null,null,4,5]"// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "";
ostringstream os;
queue<TreeNode*> q({root});
while (!q.empty()) {
TreeNode* t = q.front(); q.pop();
if (!t) {
os << "# ";
} else {
os << to_string(t->val) << " ";
q.push(t->left);
q.push(t->right);
}
}
return os.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) return nullptr;
istringstream is(data);
queue<TreeNode*> q;
string val;
is >> val;
TreeNode* res = new TreeNode(stoi(val)), *cur = res;
q.push(cur);
while (!q.empty()) {
TreeNode* t = q.front(); q.pop();
if (!(is >> val)) break;
if (val != "#") {
cur = new TreeNode(stoi(val));
q.push(cur);
t->left = cur;
}
if (!(is >> val)) break;
if (val != "#") {
cur = new TreeNode(stoi(val));
q.push(cur);
t->right = cur;
}
}
return res;
}Last updated