Skip to content

Instantly share code, notes, and snippets.

@airekans
Created July 15, 2015 05:00
Show Gist options
  • Save airekans/1c84e639a3c5719c7bd9 to your computer and use it in GitHub Desktop.
Save airekans/1c84e639a3c5719c7bd9 to your computer and use it in GitHub Desktop.
binary tree serialization, check here for the format explanation: https://leetcode.com/problems/binary-tree-inorder-traversal/
#include <queue>
#include <string>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void Serialize(const TreeNode* root, ::std::string& res)
{
if (root == NULL) {
return;
}
char int_buf[64] = "";
::std::queue<const TreeNode*> node_q;
node_q.push(root);
while (!node_q.empty()) {
const TreeNode* node = node_q.front();
node_q.pop();
if (node == NULL) {
res.append(",#");
continue;
}
node_q.push(node->left);
node_q.push(node->right);
if (res.empty()) {
snprintf(int_buf, 64, "%d", node->val);
} else {
snprintf(int_buf, 64, ",%d", node->val);
}
res.append(int_buf);
}
::std::string::size_type pos = res.find_last_not_of(",#");
res.resize(pos + 1);
}
int GetInt(const char* str, int* res)
{
int i = 0;
while (str[i] != ',' && str[i] != '\0') ++i;
*res = atoi(str);
return i;
}
TreeNode* Deserialize(const ::std::string& str)
{
if (str.empty()) {
return NULL;
}
struct NodeStat
{
TreeNode* node;
int stat;
NodeStat(TreeNode* n) : node(n), stat(0) {}
};
size_t i = 0;
::std::queue<NodeStat> parents;
TreeNode* root = NULL;
while (i < str.size()) {
if (str[i] == '#') {
assert(!parents.empty());
NodeStat& stat = parents.front();
++stat.stat;
if (stat.stat >= 2) {
parents.pop();
}
i += 2;
continue;
}
int val = 0;
int bytes = GetInt(str.c_str() + i, &val);
TreeNode* node = new TreeNode(val);
i += bytes + 1;
if (root == NULL) {
root = node;
}
if (!parents.empty()) {
NodeStat& stat = parents.front();
if (stat.stat == 0) {
stat.node->left = node;
} else {
stat.node->right = node;
}
++stat.stat;
if (stat.stat >= 2) {
parents.pop();
}
}
parents.push(NodeStat(node));
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment