Serialize and Deserialize Binary Tree
1) Please remember how to split a string by char;
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string ret;
if(root == NULL)
{
return ret;
}
list<TreeNode*> queue;
queue.push_back(root);
bool hasNextLevel = true;
while(!queue.empty() && hasNextLevel)
{
int size = queue.size();
hasNextLevel = false;
for(int i = 0; i<size; i++)
{
TreeNode* p = queue.front();
queue.pop_front();
if(p == NULL)
{
ret += "null,";
continue;
}
ret += to_string(p->val) + ",";
queue.push_back(p->left);
queue.push_back(p->right);
if(p->left != NULL || p->right != NULL)
{
hasNextLevel = true;
}
}
}
ret.pop_back();
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//cout<<data<<endl;
if(data.empty())
{
return NULL;
}
vector<string> vec = split(data, ',');
TreeNode* root = new TreeNode(stoi(vec[0]));
TreeNode*p = root;
list<TreeNode*> queue;
for(int i = 1; i<vec.size(); i++)
{
if(i%2 == 1)
{
if(vec[i] != "null")
{
TreeNode* newnode = new TreeNode(stoi(vec[i]));
p->left = newnode;
queue.push_back(newnode);
}
}
else
{
if(vec[i] != "null")
{
TreeNode* newnode = new TreeNode(stoi(vec[i]));
p->right = newnode;
queue.push_back(newnode);
}
p = queue.front();
queue.pop_front();
}
}
return root;
}
vector<string> split(const string& str, char delim)
{
vector<string> ret;
stringstream ss;
ss.str(str);
string item;
while(getline(ss, item, delim))
{
ret.push_back(item);
}
return ret;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));