Last active
August 29, 2015 13:56
-
-
Save sundeepblue/8804425 to your computer and use it in GitHub Desktop.
serialize deserialize Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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