Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Last active August 29, 2015 13:56
Show Gist options
  • Save sundeepblue/8804425 to your computer and use it in GitHub Desktop.
Save sundeepblue/8804425 to your computer and use it in GitHub Desktop.
serialize deserialize Binary Tree
// in pre-order
void serialize_btree(TreeNode *root, string &s) {
if(!root) {
s += '#';
return;
}
s += to_string(root->data);
serialize_btree(root->left, s);
serialize_btree(root->right, s);
}
// in pre-order
TreeNode* deserialize_btree(string &s, int &curr) {
if(curr > s.size()) return NULL;
if(s[curr] == '#') {
curr++;
return NULL;
}
TreeNode *root = new TreeNode(s[curr++]);
root->left = deserialize_btree(s, curr); // gist, this "curr" is different from the below "curr", since we use reference
root->right = deserialize_btree(s, curr); // gist, this "curr" is different from the above "curr"
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment