Serialization is the PRocess of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer,
or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work.
You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
1 / / 2 3 / / 4 5as"[1,2,3,null,null,4,5]"
, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
二叉树的序列化和反序列化。这里都用了广度优先的方式进行,用队列实现。实现没什么难点,注意空指针就行了。
这里遇到了坑,在序列化的时候,想着一个节点用完了,后面就没有用处了,反正后面返回的是字符串,所以每个节点的内存都释放掉了。
结果通过不了,内存出错了。可能测试的时候会出现一颗二叉树用几次的情况吧。
代码:
class Codec {public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; if(!root) return "null"; queue<TreeNode*>q; q.push(root); while(!q.empty()) { TreeNode* tmp = q.front(); q.pop(); if(!tmp) { res += "null,"; } else { res += to_string(tmp->val) + ","; q.push(tmp->left); q.push(tmp->right); } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int pos = 0, n = data.size(); data += ","; TreeNode* root = build_node(data, pos); if(!root) return NULL; queue<TreeNode*>q; q.push(root); while(!q.empty()) { TreeNode* tmp = q.front(); q.pop(); if(pos >= n) break; tmp->left = build_node(data, pos); if(tmp->left) q.push(tmp->left); if(pos >= n) break; tmp->right = build_node(data, pos); if(tmp->right) q.push(tmp->right); } return root; }private: TreeNode* build_node(const string& s, int& pos) { int end = s.find(",", pos); string tmp = s.substr(pos, end-pos); pos = end + 1; if(tmp == "null") { return NULL; } else { TreeNode *node = new TreeNode(stoi(tmp)); return node; } }};
新闻热点
疑难解答