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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
這道題讓我們對二叉搜索樹序列化和去序列化,跟之前那道Serialize and Deserialize Binary Tree極其相似,雖然題目中說編碼成的字符串要盡可能的緊湊,但是我們並沒有發現跟之前那題有何不同,而且也沒有看到能夠利用BST性質的方法,姑且就按照之前題目的解法來寫吧:
解法一:
class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { ostringstream os; serialize(root, os); return os.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream is(data); return deserialize(is); } void serialize(TreeNode* root, ostringstream& os) { if (!root) os << "# "; else { os << root->val << " "; serialize(root->left, os); serialize(root->right, os); } } TreeNode* deserialize(istringstream& is) { string val = ""; is >> val; if (val == "#") return NULL; TreeNode* node = new TreeNode(stoi(val)); node->left = deserialize(is); node->right = deserialize(is); return node; } };
另一種方法是層序遍歷的非遞歸解法,這種方法略微復雜一些,我們需要借助queue來做,本質是BFS算法,也不是很難理解,就是BFS算法的常規套路稍作修改即可,參見代碼如下:
解法二:
class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if (!root) return ""; ostringstream os; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode *t = q.front(); q.pop(); if (t) { os << t->val << " "; q.push(t->left); q.push(t->right); } else { os << "# "; } } return os.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.empty()) return NULL; istringstream is(data); queue<TreeNode*> q; string val = ""; is >> val; TreeNode *res = new TreeNode(stoi(val)), *cur = res; q.push(cur); while (!q.empty()) { TreeNode *t = q.front(); q.pop(); if (!(is >> val)) break; if (val != "#") { cur = new TreeNode(stoi(val)); q.push(cur); t->left = cur; } if (!(is >> val)) break; if (val != "#") { cur = new TreeNode(stoi(val)); q.push(cur); t->right = cur; } } return res; } };
類似題目:
Serialize and Deserialize Binary Tree
Serialize and Deserialize N-ary Tree
參考資料:
https://leetcode.com/problems/serialize-and-deserialize-bst
https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93260/easy-bfs-java